Keyboard

This application illustrates the use of the both the BufferedReader and the BufferedWriter classes for reading lines from the keyboard and writing them to a file.

One additional thing you will need is System.in. Look at its specification. Note its relation to System.out and System.err. You have been using System.out routinely; now see what it means!

import java.awt.*;
import java.io.*;

public class Keyboard  {

//  simplest kyeboard input and write to a file

  public Keyboard  ()  {
    super ();
  }  // end Keyboard  constructor

  public static void main ( String [ ] args )  {

  File outFile;
  FileOutputStream outFileStream;
  OutputStreamWriter outStreamWriter;
  BufferedWriter  outBufWriter;

  InputStreamReader inStreamReader;
  BufferedReader  inBufReader;

  String fileName;
  String path;

  String line;

  Keyboard writeAppl = new Keyboard ();

  // Instantiate and chain the InputStreamReader
  inStreamReader = new InputStreamReader ( System.in );

  // Instantiate and chain the BufferedReader
  inBufReader = new BufferedReader ( inStreamReader );

  // Instantiate the output file
  if ( args.length > 0 ) fileName = args[0];
  else {
    fileName = new String ( "testfile" );
    path = new String ( "../testdata/" );
  }
  if ( args.length > 1 ) path = args[1];
  else path = new String ( "../testdata/" );

  outFile = new File ( path, fileName );

  // Instantiate and chain the FileOutputStream
  try {
    outFileStream = new FileOutputStream ( outFile );
    }  // end try
  catch ( IOException except ) {
    return;
    }  // end catch

  // Instantiate and chain the OutputStreamWriter
  outStreamWriter = new OutputStreamWriter ( outFileStream );

  // Instantiate and chain the BufferedWriter
  outBufWriter = new BufferedWriter ( outStreamWriter );

  System.out.println ( "Writing to file: " + outFile.getName() );

  boolean more = true;
  try {
    System.out.println ("Type input lines:");
    while ( more ) {
        line = inBufReader.readLine ( );
        if (line == null ) {
            more = false;
            System.out.println ("  End Of File");
        }  // end if
        else {
        System.out.println ("  Wrote line = "+line);
            outBufWriter.write ( line );
            outBufWriter.newLine ();
        }  // end else
    }  // end while
    }  // end try
  catch ( IOException except ) {
    ;
    }  // end catch

  try {
    outBufWriter.close ();
    System.out.println ("  Program ended");
    }
  catch ( IOException except ) {
    return;
    }

  }  // end main

}  // end Keyboard