用java在Linux环境下执行shell命令,可以使用如下方法:
import java.io.IOException;
public class JavaShell
{
/**
* @param args
* @throws IOException
* @throws InterruptedException
*/
public static void main(String[] args) throws IOException, InterruptedException
{
Process p;
p = Runtime.getRuntime().exec("md5sum a.c > a.c.md5"});
if(0==p.waitFor())
{
System.out.println("Command execute result is OK!");
}
else
{
System.out.println("Command execute result is fail......");
}
}
}
但上述程序执行起来是有问题的。程序运行后,并没有正确的生成.md5文件。Runtime.getRuntime().exec的执行结果都是非0。出现这种错误的原因是因为 额外的参数(">") 被直接传送到了md5sum命令而不是送到实际的命令行。
解决这一问题的办法是将cmd串弄成一个字符串数组,并且将你想运行的程序传送到命令shell。如下面的程序所示:
import java.io.IOException;
public class JavaShell
{
/**
* @param args
* @throws IOException
* @throws InterruptedException
*/
public static void main(String[] args) throws IOException, InterruptedException
{
Process p;
p = Runtime.getRuntime().exec(new String[]{"sh","-c","md5sum a.c > a.c.md5"});
if(0==p.waitFor())
{
System.out.println("Command execute result is OK!");
}
else
{
System.out.println("Command execute result is fail......");
}
}
}
Reference:
http://hi.baidu.com/litertiger/blog/item/822a7ef049c913d47831aa19.html
http://blog.csdn.net/georgejin/archive/2010/10/13/5937877.aspx
http://hi.baidu.com/zhangtianshun/blog/item/ae632246b572b40e6a63e579.html
转自:http://www.liaoqiqi.com/blog/2011/java-call-shell-command-redirection-pipeline-problems/