简体   繁体   English

java.io.File(parent, child) 不能按预期工作

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

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.我正在尝试根据用户提供的文件名(可以是绝对的或相对的)和依赖于环境的基目录构造一个 Java File 对象。 The java doc for java.io.File(File parent, String child) says the following: 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.如果子路径名字符串是绝对的,那么它以系统相关的方式转换为相对路径名

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?我误解了 JavaDoc 吗?

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检查它是否是parent目录中的绝对路径,以及

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

to get the relative part.得到相对部分。

With your base directory expressed as a Path , eg将您的基本目录表示为Path ,例如

Path basePath = new File("C:/Temp").toPath();

you can use Path.resolve to determine the Path (or File ) for your fileName , regardless of whether it is absolute or relative:您可以使用Path.resolve来确定您的fileNamePath (或File ),无论它是绝对的还是相对的:

Path path = basePath.resolve(fileName).normalize();
File file = path.toFile();

The additional normalize here simply takes care of cleaning up any .这里额外的normalize只负责清理任何. or .. from the path...从路径。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM