Java Files  «Prev  Next»
Lesson 5 Listing File information
ObjectiveListing path information

Listing Path Information in Java

Understand how to get path information of a File object .

After you have established that a File object exists and you have used the getName() method to find out what its name is, you can determine the object's path using several methods.

Determining File Object's Path

To get the path to a file use getPath():
public String getPath()

Relative versus Absolute:

This is merely a get method that returns the path field. Therefore, the path is relative if the File object was constructed with a relative path and absolute if the File object was constructed with an absolute path. Furthermore, this method never throws IOExceptions.
This returns a string that contains the path being used for this File object. It will be 1) relative or 2) absolute depending on how the File object was created.
The next question you have to ask yourself is: Is the path
  1. relative or
  2. absolute
Consider the example below. This simple program constructs two File objects, one with a 1) relative path and one with 2) an absolute path, then prints the name and path of each object.
public class Paths {
  public static void main(String[] args) {
    File absolute = new File("/public/html/javafaq/index.html");
    File relative = new File("html/javafaq/index.html");
    System.out.println("absolute: ");
    System.out.println("relative: ");

Is it an absolute or relative path?

The isAbsolute() method returns true if the filename is an absolute path and false if it is a relative path.

public boolean isAbsolute()

Getting the absolute path

If you need the absolute path, you can use the getAbsolutePath() method:
public String getAbsolutePath()

This returns the complete, nonrelative path to the file.

Getting the canonical path

An alternative is getCanonicalPath():
public String getCanonicalPath() throws IOException

This returns the canonical form of this File object's pathname. What a canonical pathname means, and how it differs from an absolute pathname, is system-dependent.