加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Java > 正文

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

发布时间:2020-12-15 00:24:58 所属栏目:Java 来源:网络整理
导读:我正在尝试根据用户提供的文件名(可以是绝对的或相对的)和依赖于环境的基本目录来构建一个 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 pa
我正在尝试根据用户提供的文件名(可以是绝对的或相对的)和依赖于环境的基本目录来构建一个 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:Tempfile.txt

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

C:TempC:Tempfile.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());

得到相对的部分.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读