File Input and Output

There are two types of files in Java - text files and binary files. Files provide both sequential and random access. A text file is processed as a sequence of characters. A binary file is processed as a sequence of bytes. In a text file you have the illusion that the file is divided into lines. There is a special end-of-line symbol that creates this illusion. In addition you can think that there is a special end-of-file symbol that follows the last component in a file. A big advantage of text files is their portability. In binary files, the representation used varies from computer to computer. Java binary files are platform independent. They can be interpreted by any computer that supports Java.

A stream is a device for transmitting or retrieving 8-bit or byte values. A file is a collection of items stored on an external device. The Java object FileStream provides the means to access the data values but does not actually hold the file contents.

There are two independent and largely parallel systems involved in I/O. InputStream and OutputStream are used to read and write 8-bit quantities and process binary files. The alternative hierarchy has two different classes Reader and Writer that are used to read and write 16-bit Unicode character values and process text files.

The File class provides methods for dealing with files or directories. File systems are organized into a hierarchy. A path is a description of a file's location in the hierarchy. When a program is running, the program' directory is considered the current directory. Any files located in the current directory can be referred to by name alone. The relative path is the location of a file with respect to the current directory. The absolute path starts at the root directory.

public class File extends Object implements Serializable
  // Constructors
  public File ( String path );
  public File ( String path, String name );

  // Public methods
  public boolean canRead();	// is the file readable?
  public boolean canWrite();	// is the file writeable?
  public boolean delete();	// delete the file
  public boolean exists();	// does the file exist
  public long lastModified();	// when was the file last modified
  public long length();		// How many bytes does it contain
  public boolean renameTo(File f);   // rename this file to f's name

Creating a Handle to a File

A handle to a file is created by passing the name of the file to the constructor for the File object:
File inFile = new File ( "FileIO.txt" );

Reading from a Text File

A text file can be read using a Scanner object. Using the Scanner offers the advantage of using the methods that come with the Scanner class.

import java.util.Scanner;

public class ReadTextFile
  public static void main (String [] args) throws IOException 
    File inFile = new File ("input.txt");

    Scanner sc = new Scanner (inFile);
    while (sc.hasNextLine())
      String line = sc.nextLine();
      System.out.println (line);

Writing to a Text File

To write text to a file you open an output stream by using the class FileWriter. If the file does not exist a new empty file with this name is created. If the file already exists opening it erases the data in the file. If you want to append to the file use the following option when creating the FileWriter object:

FileWriter fWriter = new FileWriter (outFile, true);

The class PrintWriter has methods print(), printf() and println() that will allow us to write to a file.


public class WriteTextFile
  public static void main (String [] args) throws IOException
    File outFile = new File ("output.txt");
    FileWriter fWriter = new FileWriter (outFile);
    PrintWriter pWriter = new PrintWriter (fWriter);
    pWriter.println ("This is a line.");
    pWriter.println ("This is another line.");