主要使用Runtime和Process两个类其中如何对Process进行输入是关键尤其注意在合适的时候flush输出流
package shelltest;
import javaioBufferedReader;
import javaioIOException;
import javaioInputStreamReader;
import javaioOutputStreamWriter;
import javaioPrintWriter;
import javautilloggingLevel;
import javautilloggingLogger;
/**
*
* @author WeiLiu
*/
public class Shell {
private Process pro = null;
private Runtime runTime = null;
public Shell() {
runTime = RuntimegetRuntime();
if (runTime == null) {
Systemerrprintln(Create runtime false!);
Systemexit();
}
}
public void execueteCommand(String command) throws InterruptedException {
Systemoutprintln(************************);
Systemoutprintln(Execute command :+command);
Systemoutprintln(Result:);
try {
pro = runTimeexec(command);
BufferedReader input = new BufferedReader(new InputStreamReader(pro getInputStream()));//这个输入流是获取shell输出的
PrintWriter output= new PrintWriter(new OutputStreamWriter(progetOu tputStream()));//这个输出流主要是对Process进行输入控制用的
String line;
while ((line = inputreadLine()) != null) {
Systemoutprintln(line);
if( != lineindexOf(your name)){//当检测到提示输入时则执行输入操作
outputprint(liuwei\r\n);// \r\n 不可少否则相当于没有Enter操作
outputflush();//输入完成之后一定要flush否则一直处在等待输入的地方
}
}
Systemoutprintln(************************\n);
inputclose();
outputclose();
prodestroy();
} catch (IOException ex) {
LoggergetLogger(ShellclassgetName())log(LevelSEVERE null ex);
}
}
}