【问题标题】:How to shorten file path (get canonical path) in java?如何在java中缩短文件路径(获取规范路径)?
【发布时间】:2014-10-13 09:02:47
【问题描述】:

java中有什么方法可以缩短目录的绝对路径。

例如:

./data/../system/bin/ => ./system/bin/

【问题讨论】:

  • 这会以什么方式缩短? ./data 与 ./system 完全不同。缩短绝对路径的唯一方法是更改​​其在文件系统上的结构
  • 注意双点 /data/.. 导致 /
  • @user1902288 如果由于某种原因我必须打印路径,我想在 (./system/bin/) 上打印最短路径
  • 我的误会,对不起;)
  • @user1902288 没问题 :)

标签: java file path


【解决方案1】:

是的,使用http://docs.oracle.com/javase/7/docs/api/java/io/File.html#getCanonicalPath()

File file = new File("C:/Users/../Users");
System.out.println(file.getAbsolutePath()); // C:\Users\..\Users
System.out.println(file.getCanonicalPath()); // C:\Users

【讨论】:

  • @bugybunny 谢谢!我只需要:) @Trengot 我用if(new File(path).exists()){}检查文件是否存在@
  • 是的,它确实有效。仅当路径包含 '\u0000' 时才会抛出 IoException
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2020-04-26
  • 2014-06-28
  • 1970-01-01
  • 1970-01-01
  • 2017-08-09
  • 2016-12-06
  • 2011-12-29
相关资源
最近更新 更多