What is the difference between getPath(), getAbstolutePath(), and getCanonicalPath() in Java?

Asked 2 years ago, Updated 2 years ago, 22 views

What is the difference between getPath(), getAbstolutePath(), and getCanonicalPath() in Java? When do you use this?

java

2022-09-22 13:00

1 Answers

First, getPath() returns the path that was inserted when creating the File object. Unlike getPath() and getCanonicalPath(), getPath() also returns the location information where the program was executed.

File file = new File ("src", "tested");
System.out.println("getPath: " + file.getPath());
System.out.println("getAbsolutePath: " + file.getAbsolutePath());
System.out.println("getCanonicalPath: " + file.getCanonicalPath());

When executing the above code, getPath() returned src/test while getAbstolutePath() and getCanonicalPath() contain the path (D:\workspace\test) that executed the current program.

getPath: src\test
getAbsolutePath: D:\workspace\Test\src\test
getCanonicalPath: D:\workspace\Test\src\test

But... The absolute path and canonical path have the same results, but the difference between the two methods can be determined by using either the current path (".") or the upper path ("..").

File file = new File("../../workspace");
System.out.println("getPath: " + file.getPath());
System.out.println("getAbsolutePath: " + file.getAbsolutePath());
System.out.println("getCanonicalPath: " + file.getCanonicalPath());

The file of the workspace at the top of the current path (D:\workspace\Test) will be D:\workspace. Depending on the method of expressing this, the absolute path and the canonical path differ. The absolute path will be the form of with the path I put after the current path, and the canonical path will be the path that actually has its parent path symbol ("..") missing . There is no big difference other than being expressed in this way. It'll be the same even if there's a "... It is said that the canonical path can be referred to as a symbolic link.

getPath: ..\..\workspace
getAbsolutePath: D:\workspace\Test\..\..\workspace
getCanonicalPath: D:\workspace


2022-09-22 13:00

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.