java.io.File(parent, child) does not work as expected
I am trying to construct a Java File object based on a user provided file name (could be absolute or relative) and a environment dependent base directory. The java doc for java.io.File(File parent, String child) says the following:
If the child pathname string is absolute then it is converted i开发者_如何学Cnto a relative pathname in a system-dependent way.
That made me think that if I have the following code:
public class TestClass {
public static void main(String[] args) throws IOException {
File file = new File(new File("C:/Temp"),"C:/Temp/file.txt");
System.out.println(file.getAbsolutePath());
}
}
the output would be
C:\Temp\file.txt
and then I'd be in business because it would not really matter anymore if the user provided an absolute or relative path. But in fact, the output is
C:\Temp\C:\Temp\file.txt
Which means I have to figure out the exact relative path (or at least test different options to see if the file exists). Am I misunderstanding the JavaDoc?
If the child pathname string is absolute then it is converted into a relative pathname in a system-dependent way.
I assume this means that even if you provide an absolute path, it will be converted to (in a system dependent way), and treated as, a relative path.
Which means I have to figure out the exact relative path (or at least test different options to see if the file exists).
Yes, I believe so.
This could perhaps be easily done with
file.getAbsolutePath().startsWith(parent.getAbsolutePath());
to check if it is an absolute path to a directory in parent
, and
file.getAbsolutePath().substring(parent.getAbsolutePath().length());
to get the relative part.
With your base directory expressed as a Path
, e.g.
Path basePath = new File("C:/Temp").toPath();
you can use Path.resolve
to determine the Path
(or File
) for your fileName
, regardless of whether it is absolute or relative:
Path path = basePath.resolve(fileName).normalize();
File file = path.toFile();
The additional normalize
here simply takes care of cleaning up any .
or ..
from the path.
精彩评论