Source of TextFileOutputDemo.java


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