Use Apache Commons exec to implement the specified application to open the corresponding file

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

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.