Next: The FileOutputStream class. Up: Files. Previous: None.


The File class

Textbook: Section 14.2

Java has a large library of classes in the java.io package related to working with files. It's quite extensive and confusing. Today we're going to investigate three of the basic classes: File, FileOutputStream, and FileInputStream.

A File object represents the name of a file on the disk. It allows you to work with the file as an entire object - not looking inside the file, but asking questions about the file's attributes or doing something that works with the file as a whole.

The most basic constructor for a File takes a string as parameter giving the complete location of where the file is located.

File(String path_name)
Creates an object representing the file name based on the path provided by path_name.

For example, you might have the following.
File source = new File("CopyFile.java");
This creates a File variable source, representing the file name ``CopyFile.java''. The parameter names the file just as you would name regular files. In Unix, a path name beginning with slash (`/') is relative to the root directory, and otherwise it is relative to the current directory (from which you invoked the program). You can name directories to move down the file hierarchy (or use the ``..'' directory to move up the hierarchy).
File source2 = new File("CS160/Lab9/CopyFile.java");
File source3 = new File("/usr/people/classes/Java/csbsju");

The File object represents a file's name, not the file itself. Thus, you can create a File object to represent a name, even if a file of that name doesn't exist.

File query methods

The first set of methods that you can perform on a File object relate to answering questions about the file.

boolean exists()
Returns true if the file exists in the file system.
boolean canWrite()
Returns true if your program can write into the file.
boolean canRead()
Returns true if your program can read from the file.
String getName()
Returns the name of the file (leaving aside the names of directories in which the file lies).
long length()
Returns the number of bytes in the file.

For example:

if(!source.exists()) {
    IO.println("The file ``" + source.getName() + "'' doesn't exist.");
    System.exit(-1);
} else if(!source.canRead()) {
    IO.println("The file ``" + source.getName() + "'' exists, "
        + "but it isn't accessible.");
    System.exit(-1);
}

File manipulation methods

There are also some for manipulating the file whole.

boolean delete()
Deletes the file, returning true if successful.
boolean renameTo(File dest)
Renames the file to the name specified by dest.


Next: The FileOutputStream class. Up: Files. Previous: None.