標籤: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 實現指定應用開啟對應檔案