The example reads lines from a file, formats them, and writes them to an output file. The lines have the form:
age true/falsewhere true/false is a person's guess as to whether or not the age is correct. For example:
40 true 35 false 7 trueThe corresponding output would be:
age = 40 correct = true age = 35 correct = false age = 7 correct = trueThe program takes the input file as a command line argument and hard codes the output file.
import java.util.*; import java.io.*; public class fileio { public static void main(String[] args) throws IOException { new fileio(args); } fileio(String[] args) throws IOException { BufferedReader input_reader; Scanner line_scanner; PrintWriter fw; String nextLine; int age; boolean correct; input_reader = new BufferedReader(new FileReader(args[0])); fw = new PrintWriter( new BufferedWriter( new FileWriter("test.txt"))); // readLine() returns null when it reaches EOF while ((nextLine = input_reader.readLine()) != null) { // if the user hit return after the last line of the file, // then there is an empty last line and the while condition // will appear to succeed. The next if statement // caters to that possibility and gets us out of the // loop if there is an empty last line if (nextLine.equals("")) break; line_scanner = new Scanner(nextLine); age = line_scanner.nextInt(); correct = line_scanner.nextBoolean(); line_scanner.close(); fw.format("age = %4d correct = %b%n", age, correct); } input_reader.close(); fw.close(); } }