// FileTest.java // Demonstrates reading and writing files in Java import java.io.*; class FileTest { public static void main(String[] args) { // first, show the contents of file "foo.txt" try { BufferedReader in = new BufferedReader(new FileReader("foo.txt")); String line; while ((line = in.readLine()) != null) { System.out.println(line); } } catch (FileNotFoundException e) { System.out.println("File not found"); } catch (IOException e) { System.out.println("IOException: " + e); } // now, load the contest of the file with something else System.out.println("Now loading 5 random lines into the file"); try { FileWriter out = new FileWriter("foo.txt"); for (int i=0; i<5; i++) { String line = "line " + i + ": Random # = " + Math.random(); System.out.println("output: " + line); out.write(line + "\r\n"); } out.close(); } catch (IOException e) { System.out.println("IOException: " + e); } } }