Source of TextFileOutputDemo.java


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