在路上

 找回密码
 立即注册
在路上 站点首页 学习 查看内容

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

2016-12-20 13:17| 发布者: zhangjf| 查看: 408| 评论: 0

摘要: 在实际工作中,我们有时候需要指定某一个应用,打开某一个文件。比如用播放器打开一个MP3音乐文件,用记事本打开一个文本文件。不过有的应用需要一些额外的参数,在具体使用的时候要注意。 package test.ffm83.commo ...
在实际工作中,我们有时候需要指定某一个应用,打开某一个文件。比如用播放器打开一个MP3音乐文件,用记事本打开一个文本文件。不过有的应用需要一些额外的参数,在具体使用的时候要注意。
  1. package test.ffm83.commons.exec;
  2. import org.apache.commons.exec.CommandLine;
  3. importorg.apache.commons.exec.DefaultExecutor;
  4. importorg.apache.commons.exec.ExecuteWatchdog;
  5. importorg.apache.commons.exec.PumpStreamHandler;
  6. importorg.apache.commons.io.output.ByteArrayOutputStream;
  7. /**
  8. * 通过commonsexec指定某一个应用打开某一个文件,比如用写字本打开txt文件
  9. *@author 范芳铭
  10. */
  11. public class EasyExecFile {
  12. publicstatic void main(String[] args) {
  13. EasyExecFileexec = new EasyExecFile();
  14. exec.notepadReadFile("d:/ffm83/ffm83.txt");
  15. }
  16. publicvoid notepadReadFile(String filePath) {
  17. Stringcommand = "notepad.exe " + filePath;
  18. try{
  19. ByteArrayOutputStreamoutputStream = new ByteArrayOutputStream();
  20. ByteArrayOutputStreamerrorStream = new ByteArrayOutputStream();
  21. //命令行处理
  22. CommandLinecommandline = CommandLine.parse(command);
  23. //进行执行体
  24. DefaultExecutorexec = new DefaultExecutor();
  25. exec.setExitValues(null);
  26. //利用监视狗来设置超时
  27. ExecuteWatchdogwatchdog = new ExecuteWatchdog(60000);
  28. exec.setWatchdog(watchdog);
  29. PumpStreamHandlerstreamHandler = new PumpStreamHandler(
  30. outputStream,errorStream);
  31. exec.setStreamHandler(streamHandler);
  32. exec.execute(commandline);//执行
  33. Stringout = outputStream.toString("gbk");
  34. Stringerror = errorStream.toString("gbk");
  35. System.out.println(out);
  36. System.err.println(error);
  37. }catch (Exception e) {
  38. e.printStackTrace();
  39. }
  40. }
  41. }
  42. 运行之后,打开了对应的txt文件。将文件关闭之后,进程结束。
复制代码
转自:http://blog.csdn.net/ffm83/article/details/42266595

最新评论

小黑屋|在路上 ( 蜀ICP备15035742号-1 

;

GMT+8, 2025-8-23 04:27

Copyright 2015-2025 djqfx

返回顶部