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 5.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:
31: if (fileOpened)
32: {
33: Scanner keyboard = new Scanner(System.in);
34: System.out.println("Enter " + howMany + " lines of data:");
35: for (int counter = 1; counter <= howMany; counter++)
36: {
37: System.out.print("Line " + counter + ": ");
38: String line = keyboard.nextLine();
39: toFile.println(line);
40: } // end for
41:
42: toFile.close();
43: } // end if
44:
45: return fileOpened;
46: } // end createTextFile
47:
48: /** Displays all lines in the named text file.
49: @param fileName The file name as a string.
50: @return True if the operation is successful. */
51: public static boolean displayFile(String fileName)
52: {
53: boolean fileOpened = true;
54: try
55: {
56: Scanner fileData = new Scanner(new File(fileName));
57: System.out.println("The file " + fileName +
58: " contains the following lines:");
59: while (fileData.hasNextLine())
60: {
61: String line = fileData.nextLine();
62: System.out.println(line);
63: } // end while
64: fileData.close();
65: }
66: catch (FileNotFoundException e)
67: {
68: fileOpened = false; // Error opening the file
69: }
70:
71: return fileOpened;
72: } // end displayFile
73: } // end TextFileOperations