CIS 35A: Introduction to Java Programming

Home | Green Sheet | Lectures | Assignments | FAQ | Grades

Files

Text and Binary Files
Text files
Connect a character output stream to a file

A subset of the Writer hierarchy

Writer <>
    BufferedWriter
    PrintWriter
    OutputStreamWriter
        FileWriter

Classes used to connect a character output stream to a file

PrintWriter				contains the methods for writing data to a text stream
	->BufferedWriter	creates a buffer for the stream
		->FileWriter	connects the stream to a file

Constructors of these classes

Constructor Throws
PrintWriter(Writer[, booleanFlush]) None
BufferedWriter(Writer) None
FileWriter(File[, booleanAppend]) IOException
FileWriter(StringFileName[, booleanAppend]) IOException

How to connect a character output stream to a file without a buffer (not recommended)

FileWriter fileWriter = new FileWriter("products.txt");
PrintWriter out = new PrintWriter(fileWriter);
A more concise way to code the same thing
PrintWriter out = new PrintWriter(new FileWriter("products.txt"));

How to connect to a file with a buffer

PrintWriter out = new PrintWriter(
                  new BufferedWriter(
                  new FileWriter(productsFile)));

How to connect for an append operation

PrintWriter out = new PrintWriter(
                  new BufferedWriter(
                  new FileWriter(productsFile, true)));

How to connect with the autoflush feature turned on

PrintWriter out = new PrintWriter(
                  new BufferedWriter(
                  new FileWriter(productsFile)), true);

Notes

  • By default, if the output file already exists, it's overwritten. If that's not what you want, you can specify true for the second argument of the FileWriter constructor to append data to the file.
  • If you specify true for the second argument of the PrintWriter constructor, the autoflush feature flushes the buffer each time the println method is called.
Previous | Connect a character output stream to a file | Write to a text file | Connect a character input stream to a file | Read from a text file | Interface with file I/O | Class with a text file | Next