您的位置:首页 > 运维架构 > Linux

Java执行linux命令 获取执行结果

2014-06-04 11:29 579 查看
package test;

//java使用Runtime.exec执行linux命令 获取执行结果
//java -cp /home/ymiao/linux_java_project/classes test.ExecTest
import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.InputStream;

public class ExecTest
{
public static void main(String[] args)
{
System.out.println("test!");

String[] cmd = { "sh", "-c", "ls > FILE" };
try
{
Process ps = Runtime.getRuntime().exec(cmd);
System.out.print(loadStream(ps.getInputStream()));
System.err.print(loadStream(ps.getErrorStream()));
}
catch (IOException ioe)
{
ioe.printStackTrace();
System.out.println("IOException");
}
}

// read an input-stream into a String
static String loadStream(InputStream in) throws IOException
{
int ptr = 0;
in = new BufferedInputStream(in);
StringBuffer buffer = new StringBuffer();
while ((ptr = in.read()) != -1)
{
buffer.append((char) ptr);
}
return buffer.toString();

}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: