利用Apache commons exec 實現指定應用打開對應文件

pooi 9年前發布 | 3K 次閱讀 Java

         在實際工作中,我們有時候需要指定某一個應用,打開某一個文件。比如用播放器打開一個MP3音樂文件,用記事本打開一個文本文件。不過有的應用需要一些額外的參數,在具體使用的時候要注意。

package test.ffm83.commons.exec;

import org.apache.commons.exec.CommandLine;

importorg.apache.commons.exec.DefaultExecutor;

importorg.apache.commons.exec.ExecuteWatchdog;

importorg.apache.commons.exec.PumpStreamHandler;

importorg.apache.commons.io.output.ByteArrayOutputStream;

/**

  • 通過commonsexec指定某一個應用打開某一個文件,比如用寫字本打開txt文件

    *@author 范芳銘

    */

public class EasyExecFile {

     publicstatic void main(String[] args) {

               EasyExecFileexec = new EasyExecFile();

               exec.notepadReadFile("d:/ffm83/ffm83.txt");

     }



     publicvoid notepadReadFile(String filePath) {

               Stringcommand = "notepad.exe " + filePath;

               try{

                        ByteArrayOutputStreamoutputStream = new ByteArrayOutputStream();

                        ByteArrayOutputStreamerrorStream = new ByteArrayOutputStream();



                        //命令行處理

                        CommandLinecommandline = CommandLine.parse(command);

                        //進行執行體

                        DefaultExecutorexec = new DefaultExecutor();



                        exec.setExitValues(null);

                        //利用監視狗來設置超時

                        ExecuteWatchdogwatchdog = new ExecuteWatchdog(60000);

                        exec.setWatchdog(watchdog);



                        PumpStreamHandlerstreamHandler = new PumpStreamHandler(

                                           outputStream,errorStream);



                        exec.setStreamHandler(streamHandler);

                        exec.execute(commandline);//執行



                        Stringout = outputStream.toString("gbk");

                        Stringerror = errorStream.toString("gbk");



                        System.out.println(out);

                        System.err.println(error);

               }catch (Exception e) {

                        e.printStackTrace();

               }

     }

}

運行之后,打開了對應的txt文件。將文件關閉之后,進程結束。</pre> 轉自:http://blog.csdn.net/ffm83/article/details/42266595

 本文由用戶 pooi 自行上傳分享,僅供網友學習交流。所有權歸原作者,若您的權利被侵害,請聯系管理員。
 轉載本站原創文章,請注明出處,并保留原始鏈接、圖片水印。
 本站是一個以用戶分享為主的開源技術平臺,歡迎各類分享!