Writing Text Files

Site: Saylor Academy
Course: CS101: Introduction to Computer Science I
Book: Writing Text Files
Printed by: Guest user
Date: Wednesday, May 14, 2025, 8:07 AM

Description

This chapter explains Java's FileWriter class and how you can use it to store data in files.

1. Writing Text Files

This chapter explains how to create a text file on the hard disk and how to write character data to it.

Chapter 21 used redirection to write text files. Redirection is when output that would normally go to the monitor is sent to a disk file. The program has no control of this.

In this chapter your program creates a file and writes output to it.

Chapter Topics:

      • Class FileWriter
      • Creating a disk file
      • Closing a disk file
      • The write() method
      • Catching I/O exceptions
      • Class BufferedWriter


Question 1:

(Review: ) What is the ancestor class of all streams that do character-oriented output?

Source: Bradley Kjell, https://chortle.ccsu.edu/Java5/Notes/chap83/ch83_1.html
Creative Commons License This work is licensed under a Creative Commons Attribution-NonCommercial 4.0 License.

2. Writer


Answer:

Writer

Writer

ioHierarchyTop (1)

Review: I/O streams are either character-oriented or byte-oriented. Character-oriented I/O streams have special features for handling character data. Byte-oriented I/O is for all types of data (including characters, if you want). This chapter shows character-oriented output to a disk file using a Writer stream.

What class is used for writing characters to a file? You know that the class descends from Writer. If you do not know what class you need, look under Writer in the Java documentation.

(Recall that in these diagrams clouds show classes, dotted clouds show abstract classes, and arrows show inheritance.)


Question 2:

Does the class FileWriter seem like a likely candidate for writing characters to a file?

3. FileWriter


Answer:

Yes

FileWriter

writerHierarchy

Class FileWriter is used for output of character data to a disk file. The arrows in the diagram show inheritance. An arrow points to the parent class.

FileWriter is a kind of OutputStreamWriter, which is a kind of Writer. When you read Java documentation, you might need to look at several ancestors of the class you are interested in.

Question 3:

Say that OutputStreamWriter has a method you would like to use. Will a FileWriter object have this method?

4. Example Program


Answer:

Yes, since FileWriter inherits from OutputStreamWriter.

Example Program

import java.io.*;

class WriteTextFile
{

  public static void main ( String[] args ) throws IOException
  {
    String fileName = "reaper.txt" ;

    FileWriter writer = new FileWriter( fileName );

    writer.write( "Behold her, single in the field,\n"  );  
    writer.write( "Yon solitary Highland Lass!\n"  );  
    writer.write( "Reaping and singing by herself;\n" );  
    writer.write( "Stop here, or gently pass!\n"  );  

    writer.close();
  }
}


This example program constructs a FileWriter stream and creates a disk file in the current directory named reaper.txt. The write() method writes characters to the file. The close() method closes the file.

The next pages explain the details. For now, save the program to a file and run it.

Warning: each time you run the program it will delete any file named reaper.txt in the directory and create a new one. You might wish to check that the 20 page report that you wrote last night is not named reaper.txt.


Question 4:

Is an IOException a checked exception?

5. Example Run


Answer:

Yes, an IOException is a checked exception, and so must be caught or thrown to the caller. (More on this later.)

Example Run

C:\Programs>DIR

06/04/00  07:55p        <DIR>          .
06/04/00  07:55p        <DIR>          ..
06/04/00  07:55p                   693 WriteTextFile.class
06/04/00  07:55p                   475 WriteTextFile.java

C:\Programs>java  WriteTextFile

C:\Programs>DIR

06/04/00  07:56p        <DIR>          .
06/04/00  07:56p        <DIR>          ..
06/04/00  07:56p                   120 reaper.txt
06/04/00  07:55p                   693 WriteTextFile.class
06/04/00  07:55p                   475 WriteTextFile.java

C:\Programs>TYPE REAPER.TXT
Behold her, single in the field,
Yon solitary Highland Lass!
Reaping and singing by herself;
Stop here, or gently pass! 


To see that the program worked, use the DIR command in the command-prompt window to look at the directory, or use the Windows file browser, Explorer.

Since it is a text file, you can use the TYPE command or the cat command (in Unix) to see it on the screen, or you can double-click it in Explorer.

The listing shows that the file reaper.txt contains 120 bytes, including end of line characters.

In the Unix (or Linux) command prompt window use ls -l to see a directory listing. Use cat reaper.txt to see the contents.


Question 5:

Could you edit reaper.txt with a text editor?

6. Character Set Transformation


Answer:

Sure. It is a text file.

Character Set Transformation

charStream

The file reaper.txt is an ordinary ASCII text file, with one byte per character. Character strings inside a running Java program are two bytes per character. A Writer stream translates between the internal format and the external, disk file format.

As mentioned in the previous chapter, the disk file uses UTF ("Unicode Transformation Format") which is identical to 8-bit ASCII format for the common characters of English. In the USA, text files are usually ASCII (and therefore also UTF).


Question 6:

What do you suppose closing a file does?

7. Closing a File


Answer:

Closing a file asks the system to finish all activity with the file and to ensure that it is safely on the disk.

Closing a File

manillaFileThe file reaper.txt is an ordinary ASCII text file, with one byte per character. Character strings inside a running Java program are two bytes per character. A Writer stream translates between the internal format and the external, disk file format.

As mentioned in the previous chapter, the disk file uses UTF ("Unicode Transformation Format") which is identical to 8-bit ASCII format for the common characters of English. In the USA, text files are usually ASCII (and therefore also UTF).


Question 7:

Can a file be written while it is closed?

8. FileWriter Constructors


Answer:

No

FileWriter Constructors

Here are two (out of several) FileWriter constructors:


FileWriter(String fileName)
FileWriter(String fileName, boolean append)

The first constructor's argument fileName is the name of a disk file that will be created in the current subdirectory. If there is already a file with that name, it will be replaced.

Here is an excerpt from the example program. The FileWriter constructor creates a disk file, reaper.txt. The constructor returns a reference to the FileWriter object which is assigned to writer. Now writer can be used to write to that file.

public static void main ( String[] args ) throws IOException
{
  String fileName = "reaper.txt" ;

  FileWriter writer = new FileWriter( fileName );
  
    . . .

The second form of the constructor has an argument, append. If append is true, the constructor will open an existing file for writing without destroying its contents. If the file does not exist, it will be created.

Question 8:

What happens if the file name is not correct? 

9. IOExceptions


Answer:

An IOException is thrown.

IOExceptions

import java.io.*;

class WriteTextFile2
{

  public static void main ( String[] args ) 
  {
    String fileName = "reaper.txt" ;

    try
    {  
      // append characters to the file
      FileWriter writer = new FileWriter( fileName, true );

      writer.write( "Alone she cuts and binds the grain,\n"  );  
      writer.write( "And sings a melancholy strain;\n"  );  
      writer.write( "O listen! for the Vale profound\n" );  
      writer.write( "Is overflowing with the sound.\n\n"  );  

      writer.close();
    }
    catch ( IOException iox )
    {
      System.out.println("Problem writing " + fileName );
    }
  }
}

Most I/O methods throw an IOException when an error is encountered. A method that uses one of these I/O methods must either (1) include throws IOException in its header, or (2) perform its I/O in a try{} block and then catch IOExceptions. The above program is modified to catch exceptions.

The constructor, the write() method, and the close() method each can throw an IOException. All are caught by the catch block.

The program opens the file reaper.txt for appending. Run it and see what it does.


Question 9:

If you are running a Microsoft operating system, change the permissions of the file reaper.txt to read only.
(Right-click on the file name in Explorer and then go to properties). Now run the program again. What happens?

10. The write() Method


Answer:

An IOException is thrown by FileWriter and caught in the catch block.

The write() Method

With FileWriter use the write() method to write characters to the file. There are several write() methods with different parameters inherited from Writer and OutputStreamWriter. The example program uses a method that writes characters from a string:

public void write(String str)  throws IOException

To output numerical results as characters use string concatenation:


int answer;
. . .
stream.write( "The answer is: " + answer)

This constructs a new string by converting the data in answer into characters and concatenating them to characters from the literal. It then writes the resulting string to the disk file.


Question 10:

Does the disk file contain int data?

11. Summary of Class FileWriter


Answer:

No, the disk file is a text file and contains only characters.

Summary of Class FileWriter

Here is a list of some of the constructors and methods used with FileWriter. All of the methods are inherited from its ancestors. For a complete list of methods look at the Java documentation on the Web.

When you write() characters to a file, you are asking the operating system to write to the disk. But the operating system might not do the work until later depending on how busy it is. The flush() method ensures that all data is actually sent to the disk.


Constructors

FileWriter(String fileName) 
An IOException is thrown if the file cannot be created.

FileWriter(String fileName, boolean append)
An IOException is thrown if the file cannot be opened for appending.

Methods

public void close() throws IOException
Flush the stream and close the file.

public void flush() throws IOException
Flush the stream.

public void write(String str) throws IOException
Write a string.

Question 11:

Why not do a flush() after each write() to be sure that all the data is written to the disk?

12. File Name from User Input


Answer:

This will slow down disk I/O.

File Name from User Input

The next example program writes to a disk file named by the user. The trim() method removes leading and trailing spaces from the user data.

Two try{} blocks are used. The first catches errors in creating the file; the second catches errors in writing data to it.

import java.io.*;
import java.util.Scanner;

class CreateFile
{
  public static void main ( String[] args ) 
  {

    // Get filename and create the file
    FileWriter writer = null;
    Scanner scan = new Scanner( System.in );
    String fileName = "";
    System.out.print("Enter Filename-->");                    // Ask for the file name
    
    try
    {
      fileName = scan.next();                                  // Get the file name
      writer = new FileWriter( fileName );                     // Create the file
    }
    catch  ( IOException iox )
    {
      System.out.println("Error in creating file");            // On failure, write error message
      return;                                                  // Return 
    } 
      
    // Write the file.
    try
    {  
      writer.write( "Behold her, single in the field,\n"  );   // Write text to the file
      writer.write( "Yon solitary Highland Lass!\n"  );  
      writer.write( "Reaping and singing by herself;\n" );  
      writer.write( "Stop here, or gently pass!\n"  );  
      writer.close();                                          // Close the file
    }
    catch ( IOException iox )
    {
      System.out.println("Problem writing " + fileName );     // On failure, write error message
    }
  }
}


Question 12:

What happens (in this program) if the close() method fails?

13. The BufferedWriter Stream


Answer:

The close() method will throw an exception, which will be caught. The catch block will write an error message that is not
really correct. You could fix the error message, or add another try/catch structure to the program that deals only with closing the file.

The BufferedWriter Stream

Disk input and output is more efficient when a buffer is used. For our small example programs it doesn't matter much. However, programs that do extensive I/O should use buffers. Use BufferedWriter to do this with a character output stream.

BufferedWriter(Writer out)  
Construct a buffered character-output stream

Since a FileWriter is a Writer it is the correct type for the parameter. Here is how this might be done:

BufferedWriter out
= new BufferedWriter(new FileWriter("stuff.txt"));

Question 13:

Do all operating systems end lines of text in the same way?

14. PrintWriter


Answer:

No.

PrintWriter

printWriterPipe

Different operating systems separate lines in text files in different ways. To the annoyance of programmers everywhere, Microsoft operating systems use a two byte sequence at the end of a line of text, but Unix (and Linux) operating systems use just one byte.

The class PrintWriter is used to deal with the end-of-line problem and other frustrations of file output. PrintWriter provides many methods that are useful for "printing" characters. ("Printing" in this context means sending characters to an output destination, not usually a hard-copy printer.) The println() method uses the appropriate line separator for the operating system the program is running on.

Often a PrintWriter stream is connected to a BufferedWriter stream which is connected to a FileWriter.

For small programs, where buffering is not needed, the middle pipe (the BufferedWriter) can be omitted.

A further advantage of PrintWriter is that none of its methods (including println()) throw exceptions. Usually output is more reliable than input (because the program has control over its output), so exception handling is sometimes not needed.


Question 14:

Can a PrintWriter be used alone?

15. Updated Example


Answer:

No. It cannot be the final destination of data, so it should be connected to some other stream.

Updated Example

import java.io.*;
class WriteTextFile3
{
  public static void main ( String[] args ) 
  {
    String fileName = "reaper.txt" ;
    PrintWriter print = null;

    try
    {       
      print = new PrintWriter( new BufferedWriter( new FileWriter( fileName  ) ) );
    }
    catch ( IOException iox )
    {
      System.out.println("Problem writing " + fileName );
    }

    print.println( "No Nightingale did ever chaunt"  );  
    print.println( "More welcome notes to weary bands"  );  
    print.println( "Of travellers in some shady haunt," );  
    print.println( "Among Arabian sands."  );  

    print.close();
  }
}


The updated example program uses a BufferedWriter and a PrintWriter. The println() prints one line of text and ends each line with the correct codes for whatever operating system you are running.

Creating the file might throw an exception, so a try/catch structure is needed for the constructor. However the println() statements do not throw exceptions and can be moved outside of the structure.


Question 15:

Is close() necessary in this program?

16. Summary of Class PrintWriter


Answer:

Yes, especially when buffers are used you should flush pending output before the program ends.

Detail: The close() method of PrintWriter does not throw an IOException, so it can be outside of any try block.

Summary of Class PrintWriter

Yet another advantage of PrintWriter is that you can ask it to automatically flush its data every time a println() is executed. (But it is still a good precaution to close() the stream when you are through with it.)

Here is a list of some of the constructors and methods used with PrintWriter. For a complete list of methods refer to the Java documentation. None of the methods throw exceptions.


Constructors

PrintWriter(Writer out) 
Create a new PrintWriter and connect it to the Writer out.
Automatic line flushing is not enabled.

PrintWriter(Writer out, boolean autoFlush)
Create a new PrintWriter and connect it to the Writer out.
Automatic line flushing is enabled if autoFlush is true.

Methods

public boolean checkError()
Flush the stream. If there has been an error in output the
method returns true.

public void close()
Flush the stream and close the file.

public void flush()
Flush the stream.

public void print(char c)
Print the character neld in c.

public void print(double d)
Translate into characters and print the double value d.

public void print(float f)
Translate into characters and print the float value f.

public void print(int i)
Translate into characters and print the int value i.

public void print(String s)
Print the String s.

public void print( various other data types )
See your complete documentation.

public void println()
Terminate the current output line and (possibly) flush the stream.

public void println( various data types )
See Java on-line documentation.

Question 16:

Can you pretty much print any type of data you want?

17. Example Program


Answer:

Yes. No need to memorize that list of methods.

Example Program

Here is an example program that prints a table of powers of two. The character '\t' is the tab character.

import java.io.*;
import java.util.Scanner;

class PowerTable
{
  public static void main ( String[] args ) 
  {
    // Get filename and create the file
    PrintWriter printer = null;
    Scanner scan = new Scanner( System.in );
    String fileName = "";

    System.out.print("Enter Filename-->");  
    try
    {
      fileName = scan.next();
      
      // create the PrintWriter and enable automatic flushing
      printer = new PrintWriter( new BufferedWriter( new FileWriter( fileName )), true );
    }
    catch ( IOException iox )
    {
      System.out.println("Error in creating file");
      return;
    }
      
    // Write out the table.
    int value = 1;
    printer.println( "Power\tValue"  );
    for ( int pow=0; pow<=20; pow++ )
    {
      printer.print  ( pow   );  
      printer.print  ( '\t'  );  
      printer.println(  value  );  
      value = value*2;
    }
    printer.close();
   
  }
 
}


Question 17:

Instead of using three statements in a row, would the following have worked as well?

    out.println( pow + "\t" + value );

18. End of Chapter


Answer:

Yes. The argument pow + "\t" + value is automatically converted to a String. The method println( String ) is then called.

End of Chapter

You have reached the end this chapter. You may wish to review the following.