通过java运行linux命令。

发布于 2024-11-27 01:42:52 字数 187 浏览 1 评论 0原文

我想通过java在linux中运行nm命令。

我尝试了这段代码:

command = "nm -l file1.o > file1.txt";
Process p = Runtime.getRuntime().exec(command);

但它不起作用,代码有什么问题?

I want to run nm command in linux through java.

I tried this code :

command = "nm -l file1.o > file1.txt";
Process p = Runtime.getRuntime().exec(command);

But it's not working, what is wrong with the code?

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

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

发布评论

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

评论(3

二智少女猫性小仙女 2024-12-04 01:42:52

这不是一个可执行文件,它实际上是一个 shell 脚本。

如果您使用 -c 调用 shell,则可以执行命令:

/bin/sh -c "command > here"

That is not an executable, it is in fact a shell script.

If you invoke the shell with -c, then you can execute your command:

/bin/sh -c "command > here"
攀登最高峰 2024-12-04 01:42:52

这是您需要做的:

String command = "nm -l file1.o > file1.txt";
Process p = Runtime.getRuntime().exec(new String[]{"/bin/sh", "-c", command});

以下“简单答案”不起作用

String command = "/bin/sh -c 'nm -l file1.o > file1.txt'";
Process p = Runtime.getRuntime().exec(command);

因为 exec(String) 方法天真地使用空格作为分隔符来分割字符串,并且忽略任何引用。因此,上面的示例相当于提供以下命令/参数列表。

new String[]{"/bin/sh", "-c", "'nm", "-l", "file1.o", ">", "file1.txt'"};

Here's what you need to do:

String command = "nm -l file1.o > file1.txt";
Process p = Runtime.getRuntime().exec(new String[]{"/bin/sh", "-c", command});

The following "simple answer" WON'T WORK :

String command = "/bin/sh -c 'nm -l file1.o > file1.txt'";
Process p = Runtime.getRuntime().exec(command);

because the exec(String) method splits its the string naively using whitespace as the separator and ignoring any quoting. So the above example is equivalent to supplying the following command / argument list.

new String[]{"/bin/sh", "-c", "'nm", "-l", "file1.o", ">", "file1.txt'"};
无法回应 2024-12-04 01:42:52

管道的替代方法是读取命令的标准输出,请参阅 Java exec() 不返回管道连接命令的预期结果 例如。

您可以读取任何输出并将其写入 StringBuffer 或 OutputStream 或您喜欢的任何内容,而不是使用“> file.txt”重定向输出。

这样做的优点是您还可以读取 stderr 并查看是否存在错误(例如设备上没有剩余空间等)。 (您也可以使用“2>”使用您的方法来做到这一点)

An alternative to pipe would be to read the stdout of your command, see Java exec() does not return expected result of pipes' connected commands for an example.

Instead of redirecting the output using "> file.txt" you would read whatever the output is and write it to a StringBuffer or OutputStream or whatever you like.

This would have the advantage that you could also read stderr and see if there were errors (like no space left on device etc.). (you can also do that using "2>" using your approach)

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