【问题标题】:Compare the relation of two file paths比较两个文件路径的关系
【发布时间】:2016-09-02 07:12:21
【问题描述】:

将两个给定的文件路径视为字符串:

/path/to/dir/path/to/dir/file

在Java中,如何测试后面的文件路径是否代表磁盘上的真实文件,该文件低于或等于第一个字符串表示的目录。这里有更多示例来阐明这一点,包括此处质疑的检查函数的一些示例返回值:

/path/to/dir /path/to/dir            (true)     
/path/to/dir /path/to/dir/file       (true)
/path/to/dir /path                   (false)
/path/to/dir /path/to/dir/../../file (false)
/path/to/dir file                    (false)
/path/to/dir /path/to/dir/dir2/../   (true)

是否可以通过File 方法.getCanonicalPath 去除点,然后检查字符串级别?也许有更好的方法。我不知道File.compareTo 到底做了什么。

【问题讨论】:

  • get rid of the dots by the File method .getCanonicalPath and then check on a string level ... 听起来您知道如何回答自己的问题。我建议实施它以查看是否有效。如果您有问题,您可以随时询问您的代码。

标签: java filepath


【解决方案1】:

请使用本机路径操作。字符串操作可能会由于路径分隔符处理不当等原因引入错误。

Path path1 = Paths.get("/home").normalize();
Path path2 = Paths.get("/home/user/filename").normalize();

path2.startsWith(path1);

【讨论】:

    【解决方案2】:

    如果你有规范路径,你可以这样做:

    String path1 = "/path/to/dir"
    String path2 = "/path/to/dir/file"
    
    path2.beginsWith(path1);
    

    这个结果就是你的答案

    【讨论】:

      【解决方案3】:

      Path 类支持equals,使您能够测试两条路径是否相等。

      startsWithendsWith 方法使您能够测试路径是否以特定字符串开头或结尾。

      这些方法很容易使用。例如:

      Path path = ...;
      Path otherPath = ...;
      Path beginning = Paths.get("/home");
      Path ending = Paths.get("foo");
      
      if (path.equals(otherPath)) {
          // equality logic here
      } else if (path.startsWith(beginning)) {
          // path begins with "/home"
      } else if (path.endsWith(ending)) {
          // path ends with "foo"
      }
      

      【讨论】:

        猜你喜欢
        • 2020-01-15
        • 2019-08-08
        • 2016-06-24
        • 2012-08-25
        • 2013-06-20
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-02-05
        相关资源
        最近更新 更多