Java Reference
In-Depth Information
As with any file-handling operations, these methods must be handled with care to avoid
deleting the wrong files and folders or wiping out data. No method is available to
undelete a file or folder.
Each of the methods throws a SecurityException if the program does not have the
security to perform the file operation in question, so these exceptions need to be dealt
with through a try - catch block or a throws clause in a method declaration.
The program in Listing 15.8 converts all the text in a file to uppercase characters. The
file is pulled in using a buffered input stream, and one character is read at a time. After
the character is converted to uppercase, it is sent to a temporary file using a buffered out-
put stream. File objects are used instead of strings to indicate the files involved, which
makes it possible to rename and delete files as needed.
LISTING 15.8
The Full Text of AllCapsDemo.java
1: import java.io.*;
2:
3: public class AllCapsDemo {
4: public static void main(String[] arguments) {
5: AllCaps cap = new AllCaps(arguments[0]);
6: cap.convert();
7: }
8: }
9:
10: class AllCaps {
11: String sourceName;
12:
13: AllCaps(String sourceArg) {
14: sourceName = sourceArg;
15: }
16:
17: void convert() {
18: try {
19: // Create file objects
20: File source = new File(sourceName);
21: File temp = new File(“cap” + sourceName + “.tmp”);
22:
23: // Create input stream
24: FileReader fr = new
25: FileReader(source);
26: BufferedReader in = new
27: BufferedReader(fr);
28:
29: // Create output stream
30: FileWriter fw = new
31: FileWriter(temp);
Search WWH ::




Custom Search