Java Notes

File I/O - Text Files

Java can read several types of information from files: binary, Java objects, text, zipped files, etc. One of the most common problems is reading lines of text.

Example: Copy one file to another

This example reads text files using the classes FileReader, BufferedReader, FileWriter, and BufferedWriter. It's a main program without a graphical user interface, reading from the console.

To change this to a graphical user interface, use JFileChooser to get a File object instead console input.

  1 
  2 
  3 
  4 
  5 
  6 
  7 
  8 
  9 
 10 
 11 
 12 
 13 
 14 
 15 
 16 
 17 
 18 
 19 
 20 
 21 
 22 
 23 
 24 
 25 
 26 
 27 
 28 
 29 
 30 
 31 
 32 
 33 
 34 
 35 
 36 
 37 
 38 
 39 
 40 
 41 
 42 
 43 
 44 
 45 
 46 
 47 
 48 
 49 
 50 
 51 
 52 
 53 
 54 
 55 
 56 
 57 
 58 
 59 
 60 
 61 
 62 
 63 
 64 
 65 
 66 
 67 
 68 
// File:  io/readwrite/CopyTextFile.java
// Description: Example to show text file reading and writing.
// Author: Fred Swartz
// Date  : February 2006

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

public class CopyTextFile {

    public static void main(String args[]) {
        //... Get two file names from use.
        System.out.println("Enter a filepath to copy from, and one to copy to.");
        Scanner in = new Scanner(System.in);

        //... Create File objects.
        File inFile  = new File(in.next());  // File to read from.
        File outFile = new File(in.next());  // File to write to

        //... Enclose in try..catch because of possible io exceptions.
        try {
            copyFile(inFile, outFile);

        } catch (IOException e) {
            System.err.println(e);
            System.exit(1);
        }
    }


    //=============================================================== copyFile
    // Uses BufferedReader for file input.
    public static void copyFile(File fromFile, File toFile) throws IOException {
        BufferedReader reader = new BufferedReader(new FileReader(fromFile));
        BufferedWriter writer = new BufferedWriter(new FileWriter(toFile));

        //... Loop as long as there are input lines.
        String line = null;
        while ((line=reader.readLine()) != null) {
            writer.write(line);
            writer.newLine();   // Write system dependent end of line.
        }

        //... Close reader and writer.
        reader.close();  // Close to unlock.
        writer.close();  // Close to unlock and flush to disk.
    }


    //=============================================================== copyFile2
    // Uses Scanner for file input.
    public static void copyFile2(File fromFile, File toFile) throws IOException {
        Scanner freader = new Scanner(fromFile);
        BufferedWriter writer = new BufferedWriter(new FileWriter(toFile));

        //... Loop as long as there are input lines.
        String line = null;
        while (freader.hasNextLine()) {
            line = freader.nextLine();
            writer.write(line);
            writer.newLine();   // Write system dependent end of line.
        }

        //... Close reader and writer.
        freader.close();  // Close to unlock.
        writer.close();  // Close to unlock and flush to disk.
    }
}

GUI interface

javax.swing.JFileChooser creates a standard file dialog and allows you to easily get a File object for reading or writing. See JFileChooser.

Working with the text lines

The above program does nothing with the lines of text except write them. Typically, you need to get values from the lines. There are several useful ways to extract data from the lines.

  1. java.util.Scanner is very useful for parsing fields from a string / file.
  2. Regular expresssions provide the best way to breaking strings into tokens like words, numbers, punctuation, etc. Regular expressions are a good replacement for the deprecated java.util.StringTokenizer class. The simplest way to break the input apart is to use the String split() method.
  3. java.util.StringTokenizer is an older class for breaking strings apart into tokens. Usually Scanner or regular expressions will be a better solution, altho they require newer (1.5 and 1.4 respectively) versions of Java.