Saturday, May 27, 2023

Difference between getPath(), getCanonicalPath() and getAbsolutePath() of File in Java - Example

In Java, the File class provides several methods for working with file paths. Here are the differences between getPath(), getCanonicalPath(), and getAbsolutePath():

 getPath(): 

The getPath() method returns the path of the file or directory as it was specified when the File object was created. It may be a relative path or an absolute path depending on how the File object was instantiated. 

If the file path contains symbolic links or relative path components, getPath() does not resolve them. 

Example:


File file = new File("mydir/example.txt");
String path = file.getPath();
System.out.println(path);

Output:


mydir/example.txt

getCanonicalPath(): The getCanonicalPath() method returns the canonicalized path of the file or directory. 

It resolves the file path by removing any symbolic links, resolving relative paths, and returning the absolute path.

 It returns a standardized path representation without any unnecessary components or redundant separators.


File file = new File("mydir/../mydir/example.txt");
String canonicalPath = file.getCanonicalPath();
System.out.println(canonicalPath);

Output:


/home/user/mydir/example.txt

getAbsolutePath(): The getAbsolutePath() method returns the absolute path of the file or directory. It provides the complete path from the root of the file system. 

If the File object was created with a relative path, getAbsolutePath() resolves it to an absolute path by prepending the current working directory. 

Example:


File file = new File("mydir/example.txt");
String absolutePath = file.getAbsolutePath();
System.out.println(absolutePath);

Output:


/home/user/current-working-directory/mydir/example.txt

It's important to note that all three methods may throw IOException if the file or directory does not exist or if an I/O error occurs during path resolution.

In summary, getPath() returns the path as provided, getCanonicalPath() returns the standardized, resolved path, and getAbsolutePath() returns the absolute path by resolving relative paths against the current working directory.

No comments:

Post a Comment