Working with Text Files and File Name Filters in Java - Files and Filename Filters
(Page 3 of 5 )
In all the examples thus far, a string has been used to refer to the file that's involved in a stream operation. This often is sufficient for a program that uses files and streams, but if you want to copy files, rename files, or handle other tasks, a File object can be used.
File, which also is part of the java.io package, represents a file or folder reference. The following File constructors can be used:
File(String)—Creates a File object with the specified folder; no filename is indicated, so this refers only to a file folder.
File(String, String)—Creates a File object with the specified folder path and the specified name.
File(File, String)—Creates a File object with its path represented by the specified File and its name indicated by the specified String.
You can call several useful methods on a File object.
The exists() method returns a Boolean value indicating whether the file exists under the name and folder path established when the File object was created. If the file exists, you can use the length() method to return a long integer indicating the size of the file in bytes.
The renameTo(File) method renames the file to the name specified by the File argument. A Boolean value is returned, indicating whether the operation was successful.
The delete() or deleteOnExit() method should be called to delete a file or a folder. The delete() method attempts an immediate deletion (returning a Boolean value indicating whether it worked). The deleteOnExit() method waits to attempt deletion until the rest of the program has finished running. This method does not return a value—you couldn't do anything with the information—and the program must finish at some point for it to work.
The getName() and getPath() methods return strings containing the name and path of the file.
Several methods are useful when the File object represents a folder rather than a file.
The mkdir() method can be used to create the folder specified by the File object it is called on. It returns a Boolean value indicating success or failure. There is no comparable method to remove folders—delete() can be used on folders as well as files.
The isDirectory() method returns the Boolean value true when the File object is a folder and false otherwise.
The listFiles() method returns an array of File objects representing the contents of the folder—all its files and subfolders.
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 output 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);
32: BufferedWriter out = new
33: BufferedWriter(fw);
34:
35: boolean eof = false;
36: int inChar = 0;
37: do {
38: inChar = in.read();
39: if (inChar != -1) {
40: char outChar = Character.toUpperCase(
(char)inChar );
41: out.write(outChar);
42: } else
43: eof = true;
44: } while (!eof);
45: in.close();
46: out.close();
47:
48: boolean deleted = source.delete();
49: if (deleted)
50: temp.renameTo(source);
51: } catch (IOException e) {
52: System.out.println("Error -- " +
e.toString());
53: } catch (SecurityException se) {
54: System.out.println("Error -- " +
se.toString());
55: }
56: }
57: }
After you compile the program, you need a text file that can be converted to all capital letters. One option is to make a copy of AllCapsDemo.java and give it a name like TempFile.java.
The name of the file to convert is specified at the command line when running AllCapsDemo, as in the following SDK example:
java AllCapsDemo TempFile.java
This program does not produce any output. Load the converted file into a text editor to see the result of the application.
Next: Summary >>
More Java Articles
More By Sams Publishing
|
This article is excerpted from chapter 15 of the book Sams Teach Yourself Java 2 in 21 days, written by Roger Cadenhead and Laura Lemay (Sams, ISBN: 0672326280). Check it out today at your favorite bookstore. Buy this book now.
|
|