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:
47: /** Displays all lines in the named text file.
48: @param fileName The file name as a string.
49: @return True if the operation is successful. */
50: public static boolean displayFile(String fileName)
51: {
52: boolean fileOpened = true;
53: try
54: {
55: Scanner fileData = new Scanner(new File(fileName));
56: System.out.println("The file " + fileName +
57: " contains the following lines:");
58: while (fileData.hasNextLine())
59: {
60: String line = fileData.nextLine();
61: System.out.println(line);
62: } // end while
63: fileData.close();
64: }
65: catch (FileNotFoundException e)
66: {
67: fileOpened = false; // Error opening the file
68: }
69:
70: return fileOpened;
71: } // end displayFile
72: } // end TextFileOperations