Working with Text Files and File Name Filters in Java - Writing Text Files
(Page 2 of 5 )
The FileWriter class is used to write a character stream to a file. It's a subclass of OutputStreamWriter, which has behavior to convert Unicode character codes to bytes.
There are two FileWriter constructors: FileWriter(String) and FileWriter(String, boolean). The string indicates the name of the file that the character stream will be directed into, which can include a folder path. The optional Boolean argument should equal true if the file is to be appended to an existing text file. As with other stream-writing classes, you must take care not to accidentally overwrite an existing file when you're appending data.
Three methods of FileWriter can be used to write data to a stream:
write(int)—Writes a character
write(char[], int, int)—Writes characters from the specified character array with the indicated starting point and number of characters written
write(String, int, int)—Writes characters from the specified string with the indicated starting point and number of characters written
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 character (or characters) for the platform being used to run the program.
Tip - 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.
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.
Next: Files and Filename Filters >>
More Java Articles
More By Sams Publishing
|
This article is excerpted from chapter 15 of the book Sams Teach Yourself Java 2 in 21 days, written by Roger Cadenhead and Laura Lemay (Sams, ISBN: 0672326280). Check it out today at your favorite bookstore. Buy this book now.
|
|