Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

java.io.File(parent, child) does not work as expected

Tags:

java

file

io

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?

like image 325
Geert Avatar asked Sep 01 '11 11:09

Geert


1 Answers

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.

like image 158
aioobe Avatar answered Oct 19 '22 23:10

aioobe