Java Files  «Prev  Next»


Lesson 7 Listing File information
ObjectiveDetermining other File Information

Write a program that lists all the information about a given file.

Once we know that a File object is indeed a file and not a directory, we can determine some other important information:
  1. Is the file readable or writable?
  2. When was it last modified?
  3. What is the size of the file?

Is the file readable or writable?

The canWrite() method indicates whether you have write access to this file. It is not a bad idea to check canWrite() before trying to put data in a file.

public boolean canWrite()

The canRead() method indicates whether you have read access to this file. It is not a bad idea to check canRead() before trying to read data out of a file.

public boolean canRead()

When was the file last modified?

The lastModified() method returns the last modification time. Since the conversion between this long value and a real date is platform-dependent, you should only use this to compare modification dates of different files.

public long lastModified()

What is the size of the file?

The length() method returns the length of the file in bytes.
public long length()

Returns the length of the file denoted by this abstract pathname. The return value is unspecified if this pathname denotes a directory.
Returns:
The length, in bytes, of the file denoted by this abstract pathname, or 0L if the file does not exist. Some operating systems may return 0L for pathnames denoting system-dependent entities such as devices or pipes.

public long length()

Listing file Information - Exercise


Click on the Exercise link below to write a character-mode program that lists all the available information about files named on the command line.
Listing file Information - Exercise