Text Files in Java

A file is for storing permanent data. Java provides file operations in java.io.*. A file is viewed as a stream of characters. Files must be opened before being accessed, and characters can be read one at a time, in order, from the file.

There is a current position in the file's character stream. The current position starts out at the first character in the file, and moves one character over as a result of a character read (or write) to the file; to read the 10th character you need to first read the first 9 characters (or you need to explicitly move the current position in the file to the 10th character).

There are special hidden chars (just like there are in the stdin input stream), '\n', '\t', etc. In a file there is another special hidden char, eof, marking the end of the file.

The easiest way to read input is to create a new Scanner object from a passed File or FileInputStream object. The easiest way to write is to create a new FileWriter object from a passed File. These are not your only options, but they are the easiest ones to use.

Reading from text files in Java

  1. Create a new Scanner object from a FileInputStream object associated with an external file:
       try { 
            Scanner reader = new Scanner(new FileInputStream("infile.dat");
    
    Or you can pass in a file name as a command line argument:
    % java MyClass infile.txt
    
    "infile.txt" is passed as args[0] to main:
    public static void main(String[] args) throws IOException {
    
        // first check to see if the program was run with the command line argument
        if(args.length < 1) {
            System.out.println("Error, usage: java ClassName inputfile");
    	System.exit(1);
        }
       
        Scanner reader = new Scanner(new FileInputStream(args[0]));
    
  2. Now use Scanner methods to read from the file.

    The Scanner class is used to read in tokens from an input stream. A token is a sequence of characters of some form that correspond to valid values of certain Java types. For example:

    1. A sequence of non-white space alphabetic characters (which can be combined with some other optional characters like digits) correspond to a String token (read with next). Here are three valid String tokens ("hello", "There", "goodbye"):
          hello           There
      
      goodbye
      
      
    2. A sequence of digit characters with an optional leading '-' character is an int token (read with nextInt). Here are three valid int tokens (-123, 22, 34):
      -123  22
      34
      
      
    3. A sequence of any character tokens up to a '\n' character is a valid line token (read with nextLine). Here are three valid line tokens "hello 1234 there how", "   are   5678", "you?"):
      hello 1234 there how
          are   5678 
      you?
      

    If the input file named "infile.dat" has the following format:

    Hello  There   1234   
    CSstudents goodbye  6556
    
    it has six tokens that we can read in using the following code:
    while (filein.hasNext()) {      // while there is another token to read
        String s = filein.next();   // reads in the String tokens "Hello" "CSstudents" 
        String r = filein.next();   // reads in the String tokens "There" "goodbye"
        int x = filein.nextInt();   // reads in the int tokens 1234  6556 
        System.out.println(s + ", " + r + ", " + x);
    }
    
    Notice how the Scanner object skips over all white-space characters to the start of the next token. For example, after reading the nextInt value 1234, the current position in the file in at the '\n' char after the 4 in the int 1234. If we had next called nextLine() instead of next() to read in the next full line as a String, we would have returned an empty string since the '\n' character is part of a valid line token. Instead, we called next to read in the next valid String token "CSstudents" which skips over all leading white space (i.e. '\n') and returns the String "CSstudents".

    Also, note that this same code sequence would work if the input file was in this crazy format:

        Hello  
        
                   There   1234   CSstudents 
        
        goodbye  
        
        6556
    

Writing to text files in Java

Use a FileWriter object to write to a File.
  1. First, create a new FileWriter object:
        FileWriter f = new FileWriter(new File("outfile"));
    
  2. Then, write data to it (again the current write position moves with every value written):
    int x = 6;
    f.write("Hello " + x + "\n")
    f.write(1234 + "  goodbye\n")
    
    Will produce file contents that look like this:
    Hello 6
    1234 goodbye
    
  3. Close the file when you are done writing to it:
    f.close();