Source of AppendTextFile.java


  1: 
  2: import java.io.FileNotFoundException;
  3: import java.io.FileOutputStream;
  4: import java.io.PrintWriter;
  5: import java.util.Scanner;
  6: 
  7: public class AppendTextFile
  8: {
  9:     public static void main(String[] args)
 10:     {
 11: 
 12:                 System.out.println("Sending output to out.txt.");
 13: 
 14:         PrintWriter outputStream = null;
 15:         try
 16:         {
 17:                  System.out.println("Enter Append for append or New for a new file:");
 18:                          Scanner keyboard = new Scanner(System.in);
 19:                          String ans = keyboard.next( );
 20:                          boolean append = ans.equalsIgnoreCase("append");// true if append, false if new
 21:                         outputStream = new PrintWriter(new FileOutputStream("out.txt", append));
 22:         }
 23:         catch(FileNotFoundException e)
 24:         {
 25:             System.out.println("Error opening the file out.txt.");
 26:             System.exit(0);
 27:         }
 28: 
 29:         System.out.println("Enter three lines of text:");
 30:         String line = null;
 31:         Scanner keyboard = new Scanner(System.in);
 32:         for ( int count = 1; count <= 3; count++)
 33:         {
 34:             line = keyboard.nextLine( );
 35:             outputStream.println(count + " " + line);
 36:         }
 37:         outputStream.close( );
 38:         System.out.println("Those lines were written to out.txt.");
 39:     }
 40: }
 41: 
 42: