java如何执行终端命令?

发布于 2024-11-09 13:15:08 字数 646 浏览 0 评论 0原文

发现这很棘手;具有以下代码:

String cmd = "find /home/folder/ -type f"; 
Runtime run = Runtime.getRuntime() ; 
Process pr = run.exec(cmd); 
pr.waitFor();

我将 pr.getInputStream() 并在那里获得正确的 find 结果,没问题。但是,如果我想更具体一点并将命令设置为 cmd = "find /home/folder/ -type f -name somefile*";,输入流将为空。

现在,我认为这与交互式 shell 完成的字符串扩展有关(我想在本例中不会使用它)。在这种情况下,* 将没有任何意义,find 将查找真正名为“*”的文件(例如 \*)。因此,我尝试将命令设置为 sh -c "find /home/folder/ -type f -name somefile*"。但它也不起作用......

我错过了什么?

谢谢,

f。

Ps.:它是一个AIX机器,带有IBM的Java JVM。

Found this to be tricky; Having the following code:

String cmd = "find /home/folder/ -type f"; 
Runtime run = Runtime.getRuntime() ; 
Process pr = run.exec(cmd); 
pr.waitFor();

I'll pr.getInputStream() and have the proper find result there, no problem. However, if I want to be a bit more specific and have my command as cmd = "find /home/folder/ -type f -name somefile*";, the input stream will be empty.

Now, I thought it would be something related to the string expansions done by the interactive shell (which wouldn't be used in this case, I suppose). In this case the * would have no meaning, and find would be looking for files really named "*" (something like \*). So I've tried to have my command as sh -c "find /home/folder/ -type f -name somefile*". But it didn't work either...

What am I missing?

thanks,

f.

Ps.: It is an AIX box, with IBM's Java JVM.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

紫竹語嫣☆ 2024-11-16 13:15:08

使用 find 时我总是转义通配符:

cmd = "find /home/folder/ -type f -name somefile\\*";

I always escape the wildcard when using find:

cmd = "find /home/folder/ -type f -name somefile\\*";
画骨成沙 2024-11-16 13:15:08

我认为如果您使用 ProcessBuilder 或 Runtime.exec 方法会更好,因为它们不需要 shell 转义并且不通过 shell 运行。

I think it would be better if you use ProcessBuilder or maybe Runtime.exec methods as they don't need shell escaping and don't run through the shell.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文