用到的jar包
commons-exec-1.3-javadoc.jar
commons-exec-1.3-sources.jar
commons-exec-1.3-test-sources.jar
commons-exec-1.3-tests.jar
commons-exec-1.3.jar
commons-io-2.4.jar
import org.apache.commons.exec.CommandLine;
import org.apache.commons.exec.DefaultExecutor;
import org.apache.commons.exec.ExecuteWatchdog;
import org.apache.commons.exec.PumpStreamHandler;
import org.apache.commons.io.output.ByteArrayOutputStream;
public class Test {
public static void main(String[] args) {
Test exec = new Test();
exec.notepadReadFile("d:/a.txt");
}
public void notepadReadFile(String filePath) {
String command = "notepad.exe " + filePath;
try{
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
ByteArrayOutputStream errorStream = new ByteArrayOutputStream();
//命令行处理
CommandLine commandline = CommandLine.parse(command);
//进行执行体
DefaultExecutor exec = new DefaultExecutor();
exec.setExitValues(null);
//利用监视狗来设置超时
ExecuteWatchdog watchdog = new ExecuteWatchdog(60000);
exec.setWatchdog(watchdog);
PumpStreamHandler streamHandler = new PumpStreamHandler(
outputStream,errorStream);
exec.setStreamHandler(streamHandler);
exec.execute(commandline);//执行
String out = outputStream.toString("gbk");
String error = errorStream.toString("gbk");
System.out.println(out);
System.err.println(error);
}catch (Exception e) {
e.printStackTrace();
}
}
}