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

利用Apache commons exec 实现指定应用打开对应文件

2017-07-26 15:55 471 查看
用到的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();

}
}

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