// File: FileIO3.java // // Author: Rahul Simha // Created: Aug, 1998. // // Illustrates reading from and writing to // the same file. A file read into memory, modified // and written out again. import java.io.*; public class FileIO3 { public static void main (String[] argv) { String filename = "testdata3"; int numLines = 0; String[] lineBuffer = null; // First, we read in the file to get the size. try { FileReader fr = new FileReader (filename); LineNumberReader lr = new LineNumberReader (fr); boolean over = false; numLines = 0; do { String input_line = lr.readLine (); if (input_line != null) numLines ++; else over = true; } while (! over); lr.close(); } catch (IOException e) { System.out.println (e); } // We have now counted the number of lines and // we will read the file into a buffer. try { FileReader fr = new FileReader (filename); LineNumberReader lr = new LineNumberReader (fr); // Allocate necessary space. lineBuffer = new String[numLines]; int i = -1; boolean over = false; do { String s = lr.readLine (); if (s == null) over = true; else lineBuffer [++i] = s; } while (! over); lr.close(); } catch (IOException e) { System.out.println (e); } // Next, write the buffer out to the same file // with line numbers added. try { // Open the file for writing FileWriter fr = new FileWriter (filename); PrintWriter pw = new PrintWriter (fr); // Write from buffer with line numbers: for (int i=0; i