【问题标题】:Java - Clean file pathJava - 清理文件路径
【发布时间】:2012-04-29 21:05:46
【问题描述】:

我想清理我在应用程序中使用的路径。路径可以修改,有时我会得到类似的东西:

C:/users/Username/Desktop/\..\..\..\Windows\Web\..\..\Program Files\..\Program Files\..\Python27\

但我想要类似的东西:

C:\Python27\

这是一个例子!

如何清理路径以仅获取必要的部分?

谢谢。

【问题讨论】:

标签: java path


【解决方案1】:

如果fileName 是您的文件名字符串,则类似于:

String cleanedFilename = new File(fileName).getCanonicalPath();

应该这样做......

还有API description

【讨论】:

    【解决方案2】:

    这是我刚刚尝试过的代码。

    new File("c:/temp/..").getCanonicalPath();

    它返回'C:\',没错。 c:/temp 的父级确实是c:\

    【讨论】:

      【解决方案3】:

      您可以尝试使用 File.getCanonicalPath() 方法:

      File file = new File("my/init/path");
      String path = file.getCanonicalPath();
      

      我还没有测试,告诉我们回来!

      编辑: @MathiasSchwarz 是对的,使用 getCanonicalPath() 而不是 getAbsolutePath() (link)

      【讨论】:

      • getAbsolutePath 不需要删除 ...。唯一的保证是返回的路径不是相对的。
      猜你喜欢
      • 2012-03-12
      • 1970-01-01
      • 1970-01-01
      • 2016-08-20
      • 2010-11-02
      • 2017-12-03
      • 2011-10-17
      • 1970-01-01
      相关资源
      最近更新 更多