我正在尝试根据用户提供的文件名(可以是绝对的或相对的)和依赖于环境的基本目录来构建一个
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());
得到相对的部分.
原文地址:https://www.jb51.cc/java/126436.html
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。