利用Apache commons exec 實現指定應用開啟對應檔案

來源:互聯網
上載者:User

標籤:apache   java   commons exec   原始碼   

         在實際工作中,我們有時候需要指定某一個應用,開啟某一個檔案。比如用播放器開啟一個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檔案。將檔案關閉之後,進程結束。

 

利用Apache commons exec 實現指定應用開啟對應檔案

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.