Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the difference between getPath(), getAbsolutePath(), and getCanonicalPath() in Java?

Tags:

java

What's the difference between getPath(), getAbsolutePath(), and getCanonicalPath() in Java?

And when do I use each one?

like image 476
knt Avatar asked Jul 08 '09 16:07

knt


People also ask

What is difference between path and absolute path in Java?

If we create the file object using an abstract path, then the absolute file path is the same as the abstract file path. If we create the file object using a relative path, then the absolute file path is the path we get after resolving the relative path against the current directory.

What is getAbsolutePath in Java?

The getAbsolutePath() method is a part of File class. This function returns the absolute pathname of the given file object. If the pathname of the file object is absolute then it simply returns the path of the current file object. For Example: if we create a file object using the path as “program.

What is the difference between path and absolute path?

A path is a unique location to a file or a folder in a file system of an OS. A path to a file is a combination of / and alpha-numeric characters. An absolute path is defined as the specifying the location of a file or directory from the root directory(/).

What is getCanonicalPath?

The getCanonicalPath() method is a part of Path class. This function returns the Canonical pathname of the given file object. If the pathname of the file object is Canonical then it simply returns the path of the current file object. The Canonical path is always absolute and unique, the function removes the '.


1 Answers

Consider these filenames:

C:\temp\file.txt - This is a path, an absolute path, and a canonical path.

.\file.txt - This is a path. It's neither an absolute path nor a canonical path.

C:\temp\myapp\bin\..\\..\file.txt - This is a path and an absolute path. It's not a canonical path.

A canonical path is always an absolute path.

Converting from a path to a canonical path makes it absolute (usually tack on the current working directory so e.g. ./file.txt becomes c:/temp/file.txt). The canonical path of a file just "purifies" the path, removing and resolving stuff like ..\ and resolving symlinks (on unixes).

Also note the following example with nio.Paths:

String canonical_path_string = "C:\\Windows\\System32\\"; String absolute_path_string = "C:\\Windows\\System32\\drivers\\..\\";  System.out.println(Paths.get(canonical_path_string).getParent()); System.out.println(Paths.get(absolute_path_string).getParent()); 

While both paths refer to the same location, the output will be quite different:

C:\Windows C:\Windows\System32\drivers 
like image 127
nos Avatar answered Sep 17 '22 01:09

nos