开发者

Run linux command through java.

I wa开发者_运维技巧nt 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?


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"


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'"};


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)

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜