public class TextFileOperations
1: import java.io.File;
2: import java.io.FileNotFoundException;
3: import java.io.PrintWriter;
4: import java.util.Scanner;
5: /**
6: A class of static methods that create and display a text file of
7: user-supplied data.
8: @author Frank M. Carrano
9: @author Timothy M. Henry
10: @version 4.0
11: */
12: public class TextFileOperations
13: {
14: /** Writes a given number of lines to the named text file.
15: @param fileName The file name as a string.
16: @param howMany The positive number of lines to be written.
17: @return True if the operation is successful. */
18: public static boolean createTextFile(String fileName, int howMany)
19: {
20: boolean fileOpened = true;
21: PrintWriter toFile = null;
22: try
23: {
24: toFile = new PrintWriter(fileName);
25: }
26: catch (FileNotFoundException e)
27: {
28: fileOpened = false; // Error opening the file
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