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
aFileobject 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 ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access