Getting File Information
Problem
You need to know all you can about a given file on disk.
Solution
Use a java.io.File
object.
Discussion
The File
class has a number of
“informational” methods. To use any of these, you must
construct a File
object containing the name of the
file it is to operate upon. It should be noted up front that creating
aFile
object has no effect on the permanent filesystem; it is
only an object in Java’s memory. You must call methods on the
File
object in order to change the filesystem; as
we’ll see, there are numerous “change” methods,
such as one for creating a new (but empty) file, one for renaming a
file, etc., as well as many informational methods. Table 10-1 lists some of the informational methods.
Table 10-1. java.io.File methods
Return type |
Method name |
Meaning |
---|---|---|
|
|
True if something of that name exists |
|
|
Full name |
|
|
Relative filename |
|
|
Parent directory |
|
|
True if file is readable |
|
|
True if file is writable |
|
|
File modification time |
|
|
File size |
|
|
True if it’s a file |
|
|
True if it’s a directory (Note: it might be neither) |
You can’t change the name stored in a File
object; you simply create a new File
object each
time you need to refer to a different file.
import java.io.*; import java.util.*; /** * Report on a file's ...
Get Java Cookbook now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.