Java Reference
In-Depth Information
1
// Fig. 15.3: CreateTextFile.java
2
// Writing data to a sequential text file with class Formatter.
3
4
5
6
7
8
import java.io.FileNotFoundException;
import java.lang.SecurityException;
import java.util.Formatter;
import java.util.FormatterClosedException;
import java.util.NoSuchElementException;
import java.util.Scanner;
9
10
public class CreateTextFile
11
{
12
private static Formatter output; // outputs text to a file
13
14
public static void main(String[] args)
15
{
16
openFile();
17
addRecords();
18
closeFile();
19
}
20
21
// open file clients.txt
22
public static void openFile()
23
{
24
try
25
{
26
output = new Formatter( "clients.txt" ); // open the file
27
}
28
catch (SecurityException securityException)
29
{
30
System.err.println( "Write permission denied. Terminating." );
31
System.exit( 1 ); // terminate the program
32
}
33
catch (FileNotFoundException fileNotFoundException)
34
{
35
System.err.println( "Error opening file. Terminating." );
36
System.exit( 1 ); // terminate the program
37
}
38
}
39
40
// add records to file
41
public static void addRecords()
42
{
43
Scanner input = new Scanner(System.in);
44
System.out.printf( "%s%n%s%n? " ,
45
"Enter account number, first name, last name and balance." ,
46
"Enter end-of-file indicator to end input." );
47
48
while (input.hasNext()) // loop until end-of-file indicator
49
{
50
try
51
{
Fig. 15.3 | Writing data to a sequential text file with class Formatter . (Part 1 of 2.)
Search WWH ::




Custom Search