Source of TextFileOperations.java


  1: import java.io.FileNotFoundException;
  2: import java.io.PrintWriter;
  3: import java.util.Scanner;
  4: /**
  5:    A class of static methods that create and display a text file of
  6:    user-supplied data.
  7:    @author Frank M. Carrano
  8:    @author Timothy M. Henry
  9:    @version 5.0
 10: */
 11: public class TextFileOperations
 12: {
 13:    /** Writes a given number of lines to the named text file.
 14:        @param fileName  The file name as a string.
 15:        @param howMany  The positive number of lines to be written.
 16:        @return  True if the operation is successful. */
 17:    public static boolean createTextFile(String fileName, int howMany)
 18:    {
 19:       boolean fileOpened = true;
 20:       PrintWriter toFile = null;
 21:       try
 22:       {
 23:          toFile = new PrintWriter(fileName);
 24:       }
 25:       catch (FileNotFoundException e)
 26:       {
 27:          fileOpened = false; // Error opening the file
 28:       }
 29:       
 30:       if (fileOpened)
 31:       {
 32:          Scanner keyboard = new Scanner(System.in);
 33:          System.out.println("Enter " + howMany + " lines of data:");
 34:          for (int counter = 1; counter <= howMany; counter++)
 35:          {
 36:             System.out.print("Line " + counter + ": ");
 37:             String line = keyboard.nextLine();
 38:             toFile.println(line);
 39:          } // end for
 40:          
 41:          toFile.close();
 42:       } // end if
 43:       
 44:       return fileOpened;
 45:    } // end createTextFile
 46: } // end TextFileOperations