notes


Files

What a File is

Part of most operating systems is a file system, a way of linking names to locations on disk, organizing these names into directory structures, and providing access to these locations through these names. The locations on disk are called files. A file is basically a sequence of bytes that is named within the file system. (The file system also knows the length of the file and other information such as who can access the file and how)

To read or write a file in Java, you need to create a FileInputStream or a FileOutputStream. The simplest constructors for these take the filename as a string. These objects can read or write bytes. Usually you don't want bytes, so you have to wrap the file stream with something that will help you convert between bytes and characters or data or whatever you want. You can even write objects to files through a process known as object serialization, but I won't cover that.

As an example, say you want to write characters to a file. You need to first create a FileOutputStream, which can write bytes to the file. Then you wrap a PrintWriter around that FileOutputStream by constructing the PrintWriter with the FileOutputStream as the sole argument to the constructor. The PrintWriter then has a println() method which takes Strings and converts them into bytes, which it passes to the FileOutputStream. To read a text file, you wrap a BufferedReader around an InputStreamReader wrapped around a FileInputStream. (Trust me - this isn't as bad as it sounds and actually makes sense once you get used to it) See the example below, which opens a text file and a data file (binary file), writes to them both, closes them, reopens them for reading and reads from them both:


Some Sample Code

import java.io.*;
import java.lang.*;

public class FileTest
{
  public static void main( String[] args )
  {
    try
    {
      //prepare console input
      InputStreamReader consoleReader = new InputStreamReader(System.in);
      BufferedReader consoleInput = new BufferedReader(consoleReader);

      //prepare text file output 
      FileOutputStream textFileOut = new FileOutputStream("file.txt");
      PrintWriter textFileWriter = new PrintWriter(textFileOut);
      
      //prepare data output
      FileOutputStream binaryFileOut = new FileOutputStream("file.dat");
      DataOutputStream dataFileOut = new DataOutputStream(binaryFileOut);

      System.out.println("Enter some text to print to text file " +
        "- end with CTRL-D on empty line");
      String line;
      while ( (line = consoleInput.readLine()) != null )
      {
      textFileWriter.println(line);
      }
      textFileWriter.close();                 // close the file

      System.out.println("\nNow we'll write some data to a binary file...");
      System.out.print("Give me a real number: ");
      line = consoleInput.readLine();         // get the input
      double d = Double.parseDouble( line );  // convert to double
      dataFileOut.writeDouble(d);             // write to file

      System.out.print("Now give me an integer: ");
      line = consoleInput.readLine();         // get the input
      int i = Integer.parseInt( line );       // convert to int
      dataFileOut.writeInt(i);                // write to file
      dataFileOut.flush();                    // make sure its written to file
      binaryFileOut.close();                  // close the file

      //now, we'll read the files:

      //prepare text file input
      FileInputStream textFileIn = new FileInputStream("file.txt");
      InputStreamReader textFileReader = new InputStreamReader(textFileIn);
      BufferedReader textFileLineReader = new BufferedReader(textFileReader);

      //prepare data file input
      FileInputStream binaryFileIn = new FileInputStream("file.dat");
      DataInputStream dataFileIn = new DataInputStream(binaryFileIn);

      System.out.println("\nReading from text file:");
      while ( (line = textFileLineReader.readLine()) != null)
      {
      System.out.println(line);
      }

      System.out.println("\nReading from data file:");
      System.out.println("double: "+dataFileIn.readDouble());
      System.out.println("   int: "+dataFileIn.readInt());
    }
    catch(IOException e)
    {
      System.out.println("ERROR: IO Exception");
    }
    catch(NumberFormatException e)
    {
      System.out.println("ERROR: you entered a bad number");
    }
    catch(FileNotFoundException e)
    {
      System.out.println("ERROR: couldn't read file...?");
    }
  }
}