gpt4 book ai didi

java.io.File(parent, child) 没有按预期工作

转载 作者:搜寻专家 更新时间:2023-10-30 21:30:42 26 4
gpt4 key购买 nike

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

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

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

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

获取相关部分。

关于java.io.File(parent, child) 没有按预期工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7269696/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com