In the actual work, we sometimes need to specify an application, open a file. For example, open a MP3 music file with a player and open a text file with Notepad. Some applications, however, require some additional parameters, which should be noted in the specific use.
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;
/**
* Open a file using Commonsexec to specify an application, such as opening a TXT file in writing
* @author Fan Fangming
*/
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 ();
Command line Processing
Commandlinecommandline = commandline.parse (command);
Executing the body
Defaultexecutorexec = new Defaultexecutor ();
Exec.setexitvalues (NULL);
Using a watchdog to set timeouts
Executewatchdogwatchdog = new Executewatchdog (60000);
Exec.setwatchdog (watchdog);
Pumpstreamhandlerstreamhandler = new Pumpstreamhandler (
Outputstream,errorstream);
Exec.setstreamhandler (Streamhandler);
Exec.execute (commandline);//execution
Stringout = outputstream.tostring ("GBK");
Stringerror = errorstream.tostring ("GBK");
System.out.println (out);
SYSTEM.ERR.PRINTLN (Error);
}catch (Exception e) {
E.printstacktrace ();
}
}
}
After running, the corresponding TXT file is opened. After the file is closed, the process ends.
Use Apache Commons exec to implement the specified application to open the corresponding file