import java.io.PrintWriter; import java.io.FileWriter; import java.io.FileReader; import java.io.BufferedReader; import java.io.IOException; import java.io.FileNotFoundException; import java.util.Scanner; /* Author: James Tam Version: March 31, 2015 * Reads 4 lines of text from the user * Writes the lines, one-at-a-time to a file * Opens and reads the lines from file until the last line echoing the contents of each line onscreen. */ public class Driver { final static int MAX = 4; public static void main(String [] args) { String line = null; String [] paragraph = null; int i; Scanner in; PrintWriter pw = null; FileWriter fw = null; BufferedReader br = null; FileReader fr = null; in = new Scanner(System.in); paragraph = new String[MAX]; // Get paragraph information from the user. for (i = 0; i < MAX; i++) { System.out.print("Enter line of text: "); line = in.nextLine(); paragraph[i] = line; } // Write paragraph to file try { fw = new FileWriter("data.txt"); pw = new PrintWriter(fw); for (i = 0; i < MAX; i++) { pw.println(paragraph[i]); } fw.close(); } catch (IOException e) { System.out.println("Error writing to file"); } // Read information from file try { fr = new FileReader("data.txt"); br = new BufferedReader(fr); line = br.readLine(); if (line == null) System.out.println("Empty file, nothing to read"); // Although the program just wrote 4 lines of text it's not a good idea // to rely on a fixed file size. Consequently programs should check for // end of file. // readLine() returns a null string when end of file reached. while (line != null) { System.out.println(line); line = br.readLine(); } fr.close(); } catch (FileNotFoundException e) { System.out.println("Could not open data.txt"); } catch (IOException e) { System.out.println("Trouble reading from data.txt"); } } }