Files and I/O (Cont.)


Writing to a File
In the following example, we use the FileWriter class together with its write() method to write some text to the file we created in the previous example. Note that when you are done writing to the file, you should close it with the close() method:

WriteToFile.java (writing to a file)

 import java.io.FileWriter;
 import java.io.IOException;

 public class WriteToFile {
   public static void main( String[ ] args ) {
     try {
       Boolean trueOrFalse = Boolean.parseBoolean( args[1] );
       FileWriter myWriter = new FileWriter( args[0], trueOrFalse );
       myWriter.( "true: append | false: overwrite" );
       myWriter.close( );
       System.out.println( "Successfully wrote to the file." );
     }
     catch ( IOException e ) {
       System.out.println( "An error occurred." );
       e.printStackTrace( );
     }
   }
 }
shell> java WriteToFile              

Some of the file classes are given next (cont.):



      There are some things you learn best in calm, and some in storm.