Output

This application illustrates the use of the BufferedWriter class for writing a stream of character data to a file. It also illustrates the rather extensive use of chaining that is typical of Java I/O.

In this example, four classes are chained. You should look closely at their APIs.

BufferedWriter
OutputStreamWriter
FileOutputStream
File
import java.awt.*;
import java.io.*;

public class Output  {

//  simplest write to a file

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

  public static void main ( String [ ] args )  {

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

  String fileName;
  String path;

  String message1 = new String ( "Hello, World!" );
  String message2 = new String ( "Hello, World, again." );

  Output writeAppl = new Output ();

  // Instantiate the 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() );

  try {
    outBufWriter.write ( message1 ); outBufWriter.newLine ();
    outBufWriter.write ( message2 ); outBufWriter.newLine ();
    }
  catch ( IOException except ) {
    return;
    }


  try {
    outBufWriter.close ();
    }
  catch ( IOException except ) {
    return;
    }

  }  // end main

}  // end Output