通过java运行linux命令。
我想通过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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
这不是一个可执行文件,它实际上是一个 shell 脚本。
如果您使用 -c 调用 shell,则可以执行命令:
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:
这是您需要做的:
以下“简单答案”不起作用:
因为
exec(String)
方法天真地使用空格作为分隔符来分割字符串,并且忽略任何引用。因此,上面的示例相当于提供以下命令/参数列表。Here's what you need to do:
The following "simple answer" WON'T WORK :
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.管道的替代方法是读取命令的标准输出,请参阅 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)