如何在文件path中处理〜

我在写一个简单的命令行Java实用程序。 我希望用户能够使用~运算符来传递相对于其主目录的文件path。 所以像~/Documents/...

我的问题是有没有办法使Java自动解决这种types的path? 还是我需要扫描~运算符的文件path?

似乎这种types的function应该被烘焙到File对象中。 但似乎不是。

一个简单的path = path.replaceFirst("^~",System.getProperty("user.home")); 当从用户那里获得(在创buildFile之前)应该足以在大多数情况下工作。

这是特定于shell的扩展,因此如果存在,则需要在行的开始处replace它:

 String path = "~/xyz"; ... if (path.startsWith("~" + File.separator)) { path = System.getProperty("user.home") + path.substring(1); } File f = new File(path); ... 

正如埃德温·巴克在评论中指出的另一个答案,〜otheruser / Documents也应该正确扩展。 这是一个为我工作的function:

 public String expandPath(String path) { try { String command = "ls -d " + path; Process shellExec = Runtime.getRuntime().exec( new String[]{"bash", "-c", command}); BufferedReader reader = new BufferedReader( new InputStreamReader(shellExec.getInputStream())); String expandedPath = reader.readLine(); // Only return a new value if expansion worked. // We're reading from stdin. If there was a problem, it was written // to stderr and our result will be null. if (expandedPath != null) { path = expandedPath; } } catch (java.io.IOException ex) { // Just consider it unexpandable and return original path. } return path; } 

一个相当简化的答案,与实际的〜字符的path一起工作:

 String path = "~/Documents"; path.replaceFirst("^~", System.getProperty("user.home"));