Java Reference
In-Depth Information
The following example writes a character stream to a file using the FileWriter class and
the write( int ) method:
FileWriter letters = new FileWriter(“alphabet.txt”);
for (int i = 65; i < 91; i++)
letters.write( (char)i );
letters.close();
The close() method is used to close the stream after all characters have been sent to the
destination file. The following is the alphabet.txt file produced by this code:
ABCDEFGHIJKLMNOPQRSTUVWXYZ
The BufferedWriter class can be used to write a buffered character stream. This class's
objects are created with the BufferedWriter( Writer ) or BufferedWriter( Writer ,
int ) constructors. The Writer argument can be any of the character output stream
classes, such as FileWriter . The optional second argument is an integer indicating the
size of the buffer to use.
BufferedWriter has the same three output methods as FileWriter : write( int ) ,
write( char[] , int , int ) , and write( String , int , int ) .
Another useful output method is newLine() , which sends the preferred end-of-line char-
acter (or characters) for the platform being used to run the program.
The different end-of-line markers can create conversion hassles
when transferring files from one operating system to another, such
as when a Windows XP user uploads a file to a web server that's
running the Linux operating system. Using newLine() instead of a
literal (such as '\n' ) makes your program more user-friendly
across different platforms.
TIP
The close() method is called to close the buffered character stream and make sure that
all buffered data is sent to the stream's destination.
Files and Filename Filters
In all the examples thus far, a string has been used to refer to the file that's involved in a
stream operation. This often is sufficient for a program that uses files and streams, but if
you want to copy files, rename files, or handle other tasks, a File object can be used.
 
Search WWH ::




Custom Search