University of Toronto - Fall 2000
Department of Computer Science

Week 3 - File Input and Output

File Input and Output

Here's a complete program that reads in an integer, stores it in variable i, and then prints it out again. Input comes from the file, input.txt, and output goes to the file, output.txt.

// EchoIntFile: program to read and print one integer.

import java.io.*;

public class EchoIntFile {

	public static void main (String[] args) throws IOException {

		// Input will be from file input.txt
		BufferedReader in = new BufferedReader
				(new FileReader ("input.txt"));

		// Output will go to file output.txt
		PrintStream out = new PrintStream (new FileOutputStream
				(new File ("output.txt")));
                out.println ("Write to output file.");

                // From now on, we can use System.out for output
		// to this same output file.
		System.setOut (out);

		// Read an integer and print it.
		System.out.println ("Enter an integer: ");
		String line = in.readLine();
		int i = Integer.parseInt(line);
		System.out.println("You entered " + i);
	}
}

Input file: input.txt

55

Output file: output.txt

Write to output file.
Enter an integer:
You entered 55