Source of TextFileOutputDemo.java


  1: //TextFileOutput.java
  2: 
  3: import java.io.PrintWriter;
  4: import java.io.FileOutputStream;
  5: import java.io.FileNotFoundException;
  6: import java.util.Scanner;
  7: 
  8: public class TextFileOutputDemo
  9: {
 10:     public static void main(String[] args)
 11:     {
 12:         String fileName = "out.txt";
 13:         //The name could be read from the keyboard instead.
 14: 
 15:         PrintWriter outputStream = null;
 16:         try
 17:         {
 18:             //outputStream = new PrintWriter(fileName);
 19:             outputStream = new PrintWriter(new FileOutputStream(fileName, true));
 20:         }
 21:         catch (FileNotFoundException e)
 22:         {
 23:             System.out.println("Error opening this file: " + fileName);
 24:             System.exit(0);
 25:         }
 26: 
 27:         System.out.println("Enter three lines of text:");
 28:         Scanner keyboard = new Scanner(System.in);
 29:         for (int count = 1; count <= 3; count++)
 30:         {
 31:             String line = keyboard.nextLine();
 32:             outputStream.println(count + " " + line);
 33:         }
 34:         outputStream.close();
 35:         System.out.println("Those lines were written to " + fileName);
 36:     }
 37: }