Source of OpenFileDemo.java


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