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 into 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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With