Read and Write Text Files in Java

An I/O Stream represents an input source or an output destination. A stream can represent many different kinds of sources and destinations, including disk files, devices, other programs, and memory arrays. A file is identified by its path through the file system, beginning from the root node. For example /home/sally/statusReport, or C:\home\sally\statusReport.

Write Text Files

The java.io.PrintWriter class provides methods to write to text files. Its constructor takes a file name as the parameter; it creates a new file, or truncate the existing file to zero size.
public PrintWriter(String fileName) throws FileNotFoundException

The following code defines a class WriteFile which generates a file with 100 random numbers.

import java.io.FileNotFoundException;
import java.io.PrintWriter;
public class WriteFile
{
    public static void main(String[] args)
                throws FileNotFoundException
    {
        PrintWriter out = new PrintWriter("random.txt");
        int line = 1;
        while (line <= 100)
            out.println((line++) + ": " + Math.random());
        out.close();
    }
}

We used two methods of the java.io.PrintWriter class: println() prints out one line, and close() closes the steam and releases system resources.

Read Text Files

The class java.io.File is an abstract representation of file and directory pathnames. Together with the java.util.Scanner class, we can read text files. The following code creates a File object, and then passes it to a Scanner object.
Scanner scan = new Scanner(new File(“test.txt”));

We define a class ReadFile below which reads a text file line by line. Note that the exception FileNotFoundException “must be caught or declared to be thrown”.

import java.util.Scanner;
import java.io.File;
import java.io.FileNotFoundException;

public class ReadFile
{
    public static void main(String[] args) 
                throws FileNotFoundException
    {
        Scanner scan = new Scanner(new File("random.txt"));
        int line = 1;
        while (scan.hasNext())
        {
            String str = scan.nextLine();
            System.out.println((line++) + ": " + str);
        }
    }
}

The following code uses “try-catch” to handle the exception.

import java.util.Scanner;
import java.io.File;
import java.io.FileNotFoundException;

public class ReadFile
{
    public static void main(String[] args)
    {
        Scanner scan;
        try
        {
            scan = new Scanner(new File("test.txt"));
        }
        catch (FileNotFoundException e)
        {
            e.printStackTrace();
            return;
        }

        int line = 1;
        while (scan.hasNext())
        {
            String str = scan.nextLine();
            System.out.println((line++) + ": " + str);
        }
    }
}

Related Posts

Related document: java.io.PrintWriter, java.io.File, java.util.Scanner.

Comments

comments