Java Reference
In-Depth Information
8 System.out.println("exists returns " + f.exists());
9 System.out.println("canRead returns " + f.canRead());
10 System.out.println("length returns " + f.length());
11 System.out.println("getAbsolutePath returns "
12 + f.getAbsolutePath());
13 }
14 }
Notice that the program includes an import from the package java.io , because
the File class is part of that package. The term “io” (or I/O) is jargon used by com-
puter science professionals to mean “input/output.” Assuming you have stored the file
hamlet.txt in the same directory as the program, you'll get output like the follow-
ing when you run the program:
exists returns true
canRead returns true
length returns 191734
getAbsolutePath returns C:\data\hamlet.txt
The fact that we use a call on new to construct a File object can be misleading.
We aren't constructing an actual file by constructing this object. The File object is
an internal object that allows us to access files that already exist on the computer.
Later in the chapter we will see how to write a program that creates a file as output.
Table 6.2 lists some useful methods for File objects.
Reading a File with a Scanner
The Scanner class that we have been using since Chapter 3 is flexible in that
Scanner objects can be attached to many different kinds of input (see Figure 6.1).
Table 6.2
Useful Methods of File Objects
Method
Description
Whether or not this file exists and can be read
canRead()
Deletes the given file
delete()
Whether or not this file exists on the system
exists()
The full path where this file is located
getAbsolutePath()
The name of this file as a String , without any path attached
getName()
Whether this file represents a directory/folder on the system
isDirectory()
Whether this file represents a file (nonfolder) on the system
isFile()
The number of characters in this file
length()
Changes this file's name to the given file's name
renameTo(file)
 
Search WWH ::




Custom Search