next up previous
Next: Program for writing to Up: Unit 09 Previous: Exceptions

Writing text files

To write a string of text on a file we have to do the following:

  1. open the file for writing by creating an object of the class FileWriter associated to the name of the file, and creating an object of the class PrintWriter associated to the FileWriter object just created;
  2. write text on the file by using the print() and println() methods of the PrintWriter object;
  3. close the file when we are finished writing to it.

The Java statements that realize the three phases described above are:

// 1. opening the file for writing (creation of the file)
FileWriter f = new FileWriter("test.txt");
PrintWriter out = new PrintWriter(f);

// 2. writing text on the file
out.println("some text to write to the file");

// 3. closing the output channel and the file
out.close();
f.close();

Notes:


next up previous
Next: Program for writing to Up: Unit 09 Previous: Exceptions