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

boolean

exists( )

True if something of that name exists

String

getCanonicalPath( )

Full name

String

getName( )

Relative filename

String

getParent( )

Parent directory

boolean

canRead( )

True if file is readable

boolean

canWrite( )

True if file is writable

long

lastModified( )

File modification time

long

length( )

File size

boolean

isFile( )

True if it’s a file

boolean

isDirectory( )

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 O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.