Java Reference
In-Depth Information
52
// output new record to file; assumes valid input
53
output.format( "%d %s %s %.2f%n" , input.nextInt(),
input.next(), input.next(), input.nextDouble());
54
55
}
56
catch (FormatterClosedException formatterClosedException)
57
{
58
System.err.println( "Error writing to file. Terminating." );
59
break ;
60
}
61
catch (NoSuchElementException elementException)
62
{
63
System.err.println( "Invalid input. Please try again." );
64
input.nextLine(); // discard input so user can try again
65
}
66
67
System.out.print( "? " );
68
} // end while
69
} // end method addRecords
70
71
// close file
72
public static void closeFile()
73
{
74
if (output != null )
75
output.close();
76
}
77
} // end class CreateTextFile
Enter account number, first name, last name and balance.
Enter end-of-file indicator to end input.
? 100 Bob Blue 24.98
? 200 Steve Green -345.67
? 300 Pam White 0.00
? 400 Sam Red -42.16
? 500 Sue Yellow 224.62
? ^Z
Fig. 15.3 | Writing data to a sequential text file with class Formatter . (Part 2 of 2.)
Lines 28-32 handle the SecurityException , which occurs if the user does not have
permission to write data to the file. Lines 33-37 handle the FileNotFoundException ,
which occurs if the file does not exist and a new file cannot be created. This exception may
also occur if there's an error opening the file. In both exception handlers we call static
method System.exit and pass the value 1 . This method terminates the application. An
argument of 0 to method exit indicates successful program termination. A nonzero value,
such as 1 in this example, normally indicates that an error has occurred. This value is
passed to the command window that executed the program. The argument is useful if the
program is executed from a batch file on Windows systems or a shell script on UNIX/
Linux/Mac OS X systems. Batch files and shell scripts offer a convenient way of executing
several programs in sequence. When the first program ends, the next program begins exe-
cution. It's possible to use the argument to method exit in a batch file or shell script to
determine whether other programs should execute. For more information on batch files or
shell scripts, see your operating system's documentation.
 
Search WWH ::




Custom Search