Source of OpenFileDemo.java


  1: import java.io.FileNotFoundException;
  2: import java.io.IOException;
  3: import java.io.PrintWriter;
  4: import java.util.Scanner;
  5: 
  6: public class OpenFileDemo
  7: {
  8:         public static void main(String[] args)
  9:         {
 10:                 System.out.println("Enter file name:");
 11:                 Scanner keyboard = new Scanner(System.in);
 12:                 String fileName = keyboard.next( );
 13:                 
 14:                 PrintWriter outputStream = null;
 15:                 try
 16:                 {
 17:                         outputStream = openOutputTextFile(fileName);
 18:         }
 19:                 catch(FileNotFoundException e)
 20:                 {
 21:                         System.out.println("Error opening the file " + fileName);
 22:                         System.exit(0);
 23:                 }
 24:                 
 25:                 System.out.println("Enter nonnegative integers.");
 26:                 System.out.println("Place a negative number at the end.");
 27:                 keyboard = new Scanner(System.in);
 28: 
 29:                 int integer;
 30:                 do
 31:                 {
 32:                          integer = keyboard.nextInt();
 33:                          outputStream.println(integer);
 34:                  } while (integer >= 0);
 35: 
 36:                  System.out.print("Numbers and sentinel value ");
 37:                  System.out.println("written to the file.");
 38:                  outputStream.close();
 39:     }
 40: 
 41:         public static PrintWriter openOutputTextFile(String fileName) 
 42:                               throws FileNotFoundException
 43:         {
 44:                 PrintWriter toFile = new PrintWriter(fileName);
 45:                 return toFile;
 46:     }
 47: }