I was wondering:
What happens after I ask for an absolute path of the current file in Java?
String s = File(".").getAbsolutePath();
How does an interpreter find the path to the current file in the filesystem? Is there some OS system call for this?
Does it return the path of a jar? Or sometimes it can return the path where the file was before compilation?
CodePudding user response:
Every process has a "current directory".
From within the process, the path .
refers to this current directory.
The actual path denoted by the current directory is (can be) a parameter to the system call that created the process (see ProcessBuilder
for instance), or it can be inherited from the process that creates your process.
The current directory is an attribute of the process, and is completely unrelated to the location of the jar file. The two paths may match by coincidence.
There is no requirement that the .
path refer to a writable location, or indeed any location in a filesystem. There may not even be a file system. That is, the path .
is not required to exist at all.
CodePudding user response:
-
- For
.
and..
there is the current working directory,System.getProperty("user.dir")
, which may be different at point of excecution, like in the IDE and stand-alone..
has nothing to do with the location of the jar, but in which directoryjava
is started.
So a path "a/./b/../c" will become "a/c". As there are disk operating systems with
...
it just might be that a native call is made. Also Windows might want to replace POSIX/
with\
. - For
String to File will always be done at run time. However where the application is started, the current working directory or
.
- that depends, varies in fact. Never at compile time, even astatic File f = new File("./readme.txt");
creates an object when the class is loaded the first time.
Here File
is a class for a phyiscal disk file.
A more general class, Path
, is superior in that it can also have its path run inside a zip file, or any feasible URI that provides a file system view.
So I will use Path
for further explanation. There is a worthwile utilities class Files
with Path operations, allowing you to copy some file from inside a zip archive to some location on hard disk.
Path.absoluteFile
is the Path version of getting the absolute path (depending on the file system view).
Path toRealPath(LinkOption... options)
with optional options does disk operating native calls (for a File) when symbolic links are wanted to be replaced with the actual physical paths. /a/b.lnk/c
could actually be /d/e/c
. This call is important should you want to detect if a path unwantedly escapes some restricted directory.