import java.io.BufferedReader; import java.io.FileReader; import java.io.BufferedReader; import java.io.FileWriter; import java.io.PrintWriter; import java.io.IOException; import java.io.FileNotFoundException; /* Author: James Tam Version: 2015 Learning objective: * file input via FileReader and BufferedReader. * file output via FileWriter and PrintWriter. */ public class DriverFileExample { public static void main (String [] args) { BufferedReader br; FileReader fr; FileWriter fw; PrintWriter pw; String s = ""; String wholeString = ""; int i = 1; try { fr = new FileReader("data.txt"); br = new BufferedReader(fr); // Read text from file and append onto the end the line count // and a newline. while (s != null) { s = br.readLine(); if (s != null) { System.out.println(s); wholeString = wholeString + i + " " + s + "\n"; } i = i + 1; } br.close(); } catch (FileNotFoundException e) { System.out.println("data.txt not in current folder"); e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } // Write the appended text from above to file (includes line // numbering and extra newlines). try { fw = new FileWriter("data_appended.txt"); pw = new PrintWriter(fw); pw.write(wholeString); fw.close(); } catch (IOException e) { e.printStackTrace(); } } }