java. io. File (parent, child) does not work properly
I'm trying to build a java file object based on the file name provided by the user (which can be absolute or relative) and the basic directory dependent on the environment java. io. The Java DOC of file (file parent, string child) is represented as follows:
This reminds me 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 will be
C:\Temp\file.txt
Then I will be in business, because if the user provides an absolute or relative path, it will no longer be important But in fact, the output is
C:\Temp\C:\Temp\file.txt
This means I have to find the exact relative path (or at least test different options to see if the file exists) Did I misunderstand Javadoc?
Solution
I think this means that even if an absolute path is provided, it will be converted to (in a system dependent manner) and regarded as a relative path
Yes, I do
This may be easy to do
file.getAbsolutePath().startsWith(parent.getAbsolutePath());
Check whether it is an absolute path in the parent directory, and
file.getAbsolutePath().substring(parent.getAbsolutePath().length());
Get the opposite part