java执行shell命令
使用到Process和Runtime两个类,返回值通过Process类的getInputStream()方法获取
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
public class ReadCmdLine {
public static void main(String args[]) {
Process process = null;
List<String> processList = new ArrayList<String>();
try {
process = Runtime.getRuntime().exec("df -hl");
BufferedReader input = new BufferedReader(new InputStreamReader(process.getInputStream()));
String line = "";
while ((line = input.readLine()) != null) {
processList.add(line);
}
input.close();
} catch (IOException e) {
e.printStackTrace();
}
for (String line : processList) {
System.out.println(line);
}
}
}
java执行命令时,判断命令是否执行结束
通常我们在第一步执行完调用后,需要知道命令是否执行完毕,则需要通过wait for()来实现
Process proc = Runtime.getRuntime().exec("xx.exe");
try {
if (proc.waitFor() != 0) {
System.err.println("exit value = " +
proc.exitValue());
}
}
catch (InterruptedException e) {
System.err.println(e);
}
proc.waitfor()的返回结果如果不为0,则执行异常,为0,则命令执行正确。
解决waitfor()阻塞或者锁死的问题
原因:由于 JVM 提供标准输入和输出流的缓冲区大小是十分有限,很快的读入或者输出流将会导致进程阻塞或者锁死。
解决方法:再调用两个线程分别输出标准输出流和标准错误流,这样就可以解决标准输出和错误流缓冲区限制而导致的阻塞和锁死状态了。
解决线程阻塞和锁死的类如下:
class RunThread extends Thread
{
InputStream is;
String type;
RunThread(InputStream is, String printType)
{
this.is = is;
this.printType = printType;
}
public void run()
{
try
{
InputStreamReader isr = new InputStreamReader(is);
BufferedReader br = new BufferedReader(isr);
String line=null;
while ( (line = br.readLine()) != null)
System.out.println(PrintType + ">" + line);
} catch (IOException ioe)
{
ioe.printStackTrace();
}
}
}
执行外部命令的主函数:
public class Runpro {
public void main(String arg[]){
try {
System.out.println("cmd start");
Process p = Runtime.getRuntime().exec("pwd"); //调用Linux的相关命令
new RunThread(p.getInputStream(), "INFO").start();
new RunThread(p.getErrorStream(),"ERR").start();
int value = p.waitFor();
if(value == 0)
System.out.println("complete");
else
System.out.println("failuer");
} catch (IOException e) {
e.printStackTrace();
}
}
}