java exec 路径_java-如何在文件路径中处理〜

java-如何在文件路径中处理〜

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

我的问题是有没有办法让Java自动解决这种类型的路径? 还是我需要扫描File运算符的文件路径?

似乎应该将这种类型的功能烘焙到File对象中。 但这似乎并非如此。

Karthik Ramachandran asked 2020-01-17T18:34:24Z

5个解决方案

65 votes

从用户处获得一个简单的path = path.replaceFirst("^~", System.getProperty("user.home"));(在使用File制作出该字符之前)应该足以在大多数情况下工作-因为波浪号仅在它的目录部分中的第一个字符时才扩展到主目录。 路径。

ratchet freak answered 2020-01-17T18:34:43Z

30 votes

这是特定于Shell的扩展,因此您需要在该行的开头(如果存在)进行替换:

String path = "~/xyz";

...

if (path.startsWith("~" + File.separator)) {

path = System.getProperty("user.home") + path.substring(1);

} else if (path.startsWith("~")) {

// here you can implement reading homedir of other users if you care

throw new UnsupportedOperationException("Home dir expansion not implemented for explicit usernames");

}

File f = new File(path);

...

Petr Kozelka answered 2020-01-17T18:35:03Z

10 votes

正如Edwin Buck在对另一个答案的评论中指出的那样,〜otheruser / Documents也应该正确扩展。 这是一个对我有用的函数:

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;

}

Dave M answered 2020-01-17T18:35:24Z

5 votes

一个相当简化的答案,适用于其中带有实际〜字符的路径:

String path = "~/Documents";

path.replaceFirst("^~", System.getProperty("user.home"));

enriched answered 2020-01-17T18:35:44Z

0 votes

当用户主目录包含“ \”或其他特殊字符时,前面提到的解决方案将无法正常工作。 这对我有用:

path = path.replaceFirst("^~", Matcher.quoteReplacement(System.getProperty("user.home")));

Matthias answered 2020-01-17T18:36:04Z

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值