This application illustrates the use of theFileOutputStream
class for writing a stream of data to a file. It can accept two parameters from the commandline: a filename and a path.import java.awt.*; import java.io.*; public class FileStreamWrite { // simplest write to a file public FileStreamWrite () { super (); } // end FileStreamWrite constructor public static void main ( String [ ] args ) { String fileName; String path; File outFile; FileOutputStream outStream; String message = new String ( "Hello, World!\nHello, World, again." ); char [] messageArray; FileStreamWrite writeAppl = new FileStreamWrite (); if ( args.length > 0 ) fileName= args[0]; else { fileName = new String ( "testfile" ); path = new String ( "/afs/unc/home/jbs/public_html/java/wwwp/lecture_8" ); } if ( args.length > 1 ) path = args[1]; else path = new String ( "/afs/unc/home/jbs/public_html/java/wwwp/lecture_8" ); outFile = new File ( path, fileName ); try { outStream = new FileOutputStream ( outFile ); } catch ( IOException except ) { return; } System.out.println ( "Writing to file: " + outFile.getName() ); messageArray = message.toCharArray (); for ( int i = 0; i < messageArray.length; i++ ) { try {outStream.write ( (byte)messageArray [ i ] ); } catch ( IOException except ) { return; } } // end for try {outStream.close (); } catch ( IOException except ) { return; } } // end main } // end FileStreamWrite