This application illustrates the use of the
PrintWriterclass for writing a stream of character data to a file. It also illustrates the use of chaining that is typical of Java I/O.In this example, three classes are chained. You should look closely at their APIs.
- PrintWriter
- 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; PrintWriter outPrintWriter; 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 ( "." ); } if ( args.length > 1 ) path = args[1]; else path = new String ( "." ); // Instantiate the file object 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 PrintWriter outPrintWriter = new PrintWriter ( outFileStream ); System.out.println ( "Writing to file: " + outFile.getName() ); outPrintWriter.println ( message1 ); outPrintWriter.println ( message2 ); // flush buffer outPrintWriter.flush(); // messages to user System.out.println ( message1 ); System.out.println ( message2 ); } // end main } // end Output