Reading Data from a File

This chapter discusses Java's FileReader and BufferedReader classes in detail. FileReader and BufferedReader classes are used together when reading data from an external file. The use of the BufferedReader class allows data to be buffered as it is read from a file before manipulating it. The readLine() method of the BufferedReader class reads a line of text from a character-oriented input stream, and puts it into a new String object.

13. Complete Program


Answer:

click.. click.. click.. click.. click

Complete Program

Here is the complete program, suitable for copying to an editor, saving to a file, and running.

              
import java.io.*;

class CopyMaker
{
  String sourceName, destName;
  BufferedReader source;
  PrintWriter dest;
  String line;

  CopyMaker ( String source, String dest )
  {
    sourceName = source;
    destName   = dest;
  }

  private boolean openFiles()  // return true if files open, else false
  {
    // open the source
    try
    {      
      source = new BufferedReader(new FileReader( sourceName ));
    }
    catch ( IOException iox )
    {
      System.out.println("Problem opening " + sourceName );
      return false;
    }
    // open the destination
    try
    {      
      dest = new PrintWriter( new BufferedWriter(new FileWriter( destName )) );
    }
    catch ( IOException iox )
    {
      System.out.println("Problem opening " + destName );
      return false;
    }
    return true;
  }

  private void copyFiles()   
  {
    try
    {      
      line = source.readLine();
      while ( line != null )
      {
        dest.println(line);
        line = source.readLine();
      }
    }
    catch ( IOException iox )
    {
      System.out.println("Problem reading or writing" );
    }
  }

  private void closeFiles()   
  {
    // close the source
    try
    {      
      source.close();
    }
    catch ( IOException iox )
    {
      System.out.println("Problem closing " + sourceName );
    }
    // close the destination
    dest.close();
  }

  public static void main ( String[] args ) 
  {
    if ( args.length == 3 && args[1].toUpperCase().equals("TO") )
    {
      CopyMaker cp = new CopyMaker( args[0], args[2] );
      if ( cp.openFiles() )
      {
        cp.copyFiles() ; 
        cp.closeFiles() ;
       }
    }
    else
      System.out.println("java CopyTextFile source to destination");
  }

}

Question 13:

Does this program make an exact copy of the input file? Hint: what if the original file was made on a Unix computer and that the copy program was running on a Windows computer?