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

来源:互联网 发布:有什么看书软件 编辑:程序博客网 时间:2024/05/22 04:47

用到的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();         } }} 


原创粉丝点击