/* BasicFileTest2.java CIS 160 David Klick 2005-09-09 Demonstration of basic file handling. */ import java.io.BufferedReader; import java.io.FileReader; import java.io.IOException; import java.io.PrintWriter; public class BasicFileTest2 { public static void main(String[] args) throws IOException { String s; int number, total = 0; // create file PrintWriter outfile = new PrintWriter("ftest.txt"); for (int i=1; i<=10; i++) { outfile.println(100-i); } outfile.close(); // read file back in FileReader fr = new FileReader("ftest.txt"); BufferedReader infile = new BufferedReader(fr); s = infile.readLine(); while (s != null) { System.out.println(s); try { number = Integer.parseInt(s); total += number; } catch (NumberFormatException e) { System.out.println("Invalid number encountered"); } s = infile.readLine(); } infile.close(); fr.close(); System.out.println("Total: " + total); } } /* Sample output: 99 98 97 96 95 94 93 92 91 90 Total: 945 */