/** This short program practices file input and output. Generally there are * three steps to doing file I/O: * 1. Set up the input and output "streams" to refer to the relevant files. * 2. Read lines of text, parse them as needed. The BufferedReader class * includes functions that allow us to read individual characters, or * whole lines, but nothing else. On the other hand, for output, the * PrintWriter is more flexible -- we can write values or objects as we * would normally do with the Screen. * 3. Close the streams when done. * The reason why we use buffers to handle file I/O is because of efficiency. * The basic FileReader and FileWriter are designed only to handle individual * bytes, and often we have lots of data to read or write. A buffer is an * area within main memory that acts like a "waiting room" for data transfers * between the program and disk. For instance, for output, we collect the * output in the output buffer until it's time to finally write to disk, which * takes place with a call to flush() or close(). */ import java.io.*; public class FileIO { public static void main(String [] args) throws IOException { // set up files for input and output BufferedReader input = new BufferedReader(new FileReader("coleridge.txt")); PrintWriter output = new PrintWriter(new FileWriter("stats.txt")); // process the input -- read lines one at a time, and determine their length // In a more sophisticated application, we would actually parse the // input line using a StringTokenizer. // Note that we don't know in advance how many lines there are, so we // read until the readLine() function returns null (meaning no more input) // Notice the output goes to a file. int lineNumber = 0; while (true) { String line = input.readLine(); if (line == null) break; ++lineNumber; output.println("Length of line " + lineNumber + " is " + line.length()); } // Close the streams. input.close(); output.close(); } }