java.io.File(parent,child)无法正常工作

我正在尝试根据用户提供的文件名(可以是绝对的或相对的)和依赖于环境的基本目录来构建一个 Java File对象. java.io.File(File parent,String child)的java doc表示如下:

If the child pathname string is absolute then it is converted into a relative pathname in a system-dependent way.

这让我想到,如果我有以下代码

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());
    }
}

输出将是

C:\Temp\file.txt

然后我会在业务,因为如果用户提供了一个绝对或相对的路径,它不会再重要了.但事实上,输出

C:\Temp\C:\Temp\file.txt

这意味着我必须找出确切的相对路径(或至少测试不同的选项来查看文件是否存在).我误解了JavaDoc吗?

解决方法

If the child pathname string is absolute then it is converted into a relative pathname in a system-dependent way.

我认为这意味着即使提供绝对路径,它将被转换为(以系统依赖的方式),并被视为相对路径.

Which means I have to figure out the exact relative path (or at least test different options to see if the file exists).

是的,我相信.

这可能很容易完成

file.getAbsolutePath().startsWith(parent.getAbsolutePath());

检查它是否是父目录中的绝对路径,以及

file.getAbsolutePath().substring(parent.getAbsolutePath().length());

得到相对的部分.

相关文章

最近看了一下学习资料,感觉进制转换其实还是挺有意思的,尤...
/*HashSet 基本操作 * --set:元素是无序的,存入和取出顺序不...
/*list 基本操作 * * List a=new List(); * 增 * a.add(inde...
/* * 内部类 * */ 1 class OutClass{ 2 //定义外部类的成员变...
集合的操作Iterator、Collection、Set和HashSet关系Iterator...
接口中常量的修饰关键字:public,static,final(常量)函数...