`
linsl
  • 浏览: 71714 次
  • 性别: Icon_minigender_1
  • 来自: 南京
社区版块
存档分类
最新评论

Execute an external program(转载)

    博客分类:
  • java
阅读更多

原文地址:http://www.rgagnon.com/javadetails/java-0014.html

Using Runtime.exec()

This example will capture the output (from stdio) of an external program.

import java.io.*;

public class CmdExec {



  public static void main(String argv[]) {

    try {

      String line;

      Process p = Runtime.getRuntime().exec

        (System.getenv("windir") +"\\system32\\"+"tree.com /A");

      BufferedReader input =

        new BufferedReader

          (new InputStreamReader(p.getInputStream()));

      while ((line = input.readLine()) != null) {

        System.out.println(line);

      }

      input.close();

    }

    catch (Exception err) {

      err.printStackTrace();

    }

  }

}

Windows CMD (or BAT) file and retrieve the errorlevel or exitcode

// win xp

import java.io.*;

public class CmdExec {

  public static void main(String argv[]) {

    try {

      String line;

      Process p = Runtime.getRuntime().exec("test.cmd");

      p.waitFor();

      System.out.println(p.exitValue());

    }

    catch (Exception err) {

      err.printStackTrace();

    }

  }

}

test.cmd (set the errorlevel manually)

@echo hello world

@exit 42

test.cmd (set the errorlevel 1 (problem detected)

@java -garbage

test.cmd (set the errorlevel 0 (execution Ok)

@java -version

Launch a Unix script

String[] cmd = {"/bin/sh", "-c", "ls > hello"};

Runtime.getRuntime().exec(cmd);

Using the ProcessBuilder

Since 1.5, the ProcessBuilder class provides more controls overs the process to be started. It's possible to set a starting directory.

   

import java.io.*;

import java.util.*;



public class CmdProcessBuilder {

  public static void main(String args[]) 

     throws InterruptedException,IOException 

  {

    List<String> command = new ArrayList<String>();

    command.add(System.getenv("windir") +"\\system32\\"+"tree.com");

    command.add("/A");



    ProcessBuilder builder = new ProcessBuilder(command);

    Map<String, String> environ = builder.environment();

    builder.directory(new File(System.getenv("temp")));



    System.out.println("Directory : " + System.getenv("temp") );

    final Process process = builder.start();

    InputStream is = process.getInputStream();

    InputStreamReader isr = new InputStreamReader(is);

    BufferedReader br = new BufferedReader(isr);

    String line;

    while ((line = br.readLine()) != null) {

      System.out.println(line);

    }

    System.out.println("Program terminated!");

  }

}

Windows rundll32 utility

Windows File association
Any program using the Windows file association mechanism can be started with the rundll32 utility.

// "file" is the filename of the data file 

//  ex. myresume.doc 

//  to start Word if the doc extension is associated with it.

Runtime.getRuntime().exec

  ("rundll32 SHELL32.DLL,ShellExec_RunDLL " + file.getAbsolutePath());

See also this HowTo about the new Desktop API, the recommended solution (but you need JDK1.6).
See also this one to open the default browser.

The following example start a Dial-up connection on the Win plateform :

[Dialup.java]

public class Dialup {

  public static void main(String[] args) throws Exception {

    Process p = Runtime.getRuntime()

      .exec("rundll32.exe rnaui.dll,RnaDial MyConnection");

    p.waitFor();

    System.out.println("Done.");

  }

}

The "MyConnection" is the DUN and it's case sensitive.

You still need to press ENTER to CONNECT, there is an option in the Connection properties to connect automatically.

On NT and W2K, rnaui.dll is not available. Use rasdial.exe instead.

rasdial "connection name"

rasdial "connection name" /d to drop

rasdial /? for more options

PDF (Windows only)

public class ShowPDF {

  public static void main(String[] args) throws Exception {

    Process p = 

      Runtime.getRuntime()

        .exec("rundll32 url.dll,FileProtocolHandler c:/pdf/mypdf.pdf");

    p.waitFor();

    System.out.println("Done.");

  }

}

PDF (Mac only)

public class ShowPDF {

  public static void main (String[] args) throws Exception{

    Process p = Runtime.getRuntime().exec("open /Documents/mypdf.pdf");

  }

}

More runddl32 examples


Path to executable with spaces in them

You can include a path for the program to be executed. On the Win plateform, you need to put the path in quotes if the path contains spaces .

 

public class Test {

  public static void main(String[] args) throws Exception {

    Process p = Runtime.getRuntime().exec(

       "\"c:/program files/windows/notepad.exe\"");

    p.waitFor();

  }

}

If you need to pass arguments , it's safer to a String array especially if they contain spaces.

String[] cmd = { "myProgram.exe", "-o=This is an option" };

Runtime.getRuntime().exec(cmd);

If using the start command and the path of the file to be started contains a space then you must specified a title to the start command.

String fileName = "c:\\Applications\\My Documents\\test.doc";

String[] commands = {"cmd", "/c", "start", "\"DummyTitle\"",fileName};

Runtime.getRuntime().exec(commands);


VBSCRIPT

// Win9x

Runtime.getRuntime().exec("start myscript.vbs");



// WinNT

Runtime.getRuntime().exec("cmd /c start myscript.vbs");



or



// with a visible console

Runtime.getRuntime().exec("cscript myscript.vbs");



// with no visible console

Runtime.getRuntime().exec("wscript myscript.vbs");

HTML Help (Windows only)

Runtime.getRuntime().exec("hh.exe myhelpfile.chm");

Start Excel

import java.io.IOException;



class StartExcel {

    public static void main(String args[])

        throws IOException

    {

        Runtime.getRuntime().exec("cmd /c start excel.exe");

    }

}

To load a worksheet

import java.io.IOException;



class StartExcel {

    public static void main(String args[])

        throws IOException

    {

        String fileName = "c:\\temp\\xls\\test2.xls";

        String[] commands = {"cmd", "/c", "start", "\"DummyTitle\"",fileName};

        Runtime.getRuntime().exec(commands);

    }

}

分享到:
评论

相关推荐

    Small HTTP server

    GZip compression support with an external Zlib library. Last version 3.05.86 For Windows shttp3.exe (141Kb) MD5(shttp3.exe) = d4956a781b867045ca65931d813608e3 For Linux shttplnx.tgz (122Kb) MD5...

    计算机英语资料.doc

    run(program):execute; carry out 运行(程序) cable:电缆(eg: cable modern) instruction:指令(eg:Instructions Cache) terminal:终端 enhance:加强 process:处理,处理过程(eg:Central Processing Unit(CPU)) ...

    Programming.the.BeagleBone.Black.epub

    Easy-to-follow plans show you how to wire up and program a Web-controlled roving robot and an e-mail notifier that lights an incandescent lamp. Set up the BeagleBone Black and explore its features ...

    GAMS Python API documentation 24.0

    If external file communication is not an issue in a particular Python application, temporary directories and files will be managed by objects in the namespace. With the exception of GamsWorkspace ...

    C Programming

    - **Getting Values into the Program**: Discussion on how to read values from external sources, such as keyboard input, and store them in variables. #### Writing a Program This section provides ...

    Using LUA with Visual C++ (Introduction)

    I prefer lua_pcall above lua_call because the later one will terminate the program if there was an error. The lua_call takes three parameters and the lua_pcall function takes four parameters : LUA_...

    微软内部资料-SQL性能优化3

    In our example, if one transaction (T1) holds an exclusive lock at the table level, and another transaction (T2) holds an exclusive lock at the row level, each of the transactions believe they have ...

    cirris operation manual

    - Printer (if included as an option) - Add-on scanners (if included) #### You May Have Received In addition to the standard items, depending on the configuration and options selected, you may also ...

    INTRODUCTION TO PYTHON SCRIPTING FOR MAYA ARTISTS.

    - **Built-In and Third-Party Modules:** Python includes many built-in modules, such as math and datetime, and supports third-party modules through external libraries like NumPy and Pandas. **Files ...

    csapp-shell-labcsapp-shell-labcsapp-shell-lab

    In this lab assignment, the primary objective is to deepen your understanding of process control and signaling by creating a simple Unix shell program that supports job control. The assignment is ...

    Java邮件开发Fundamentals of the JavaMail API

    your program to use IMAP instead of POP and expect everything in IMAP to be supported. Assuming your mail server supports IMAP, your JavaMail-based program can take Fundamentals of the JavaMail API...

    经典小巧的表格组件 EhLib4.14

     global event that execute SQL expression with parameters using your  favorite access data base engine and return DataSet-cursor.  The technology is represented by two main component:  ...

    EhLib-delphi

     global event that execute SQL expression with parameters using your  favorite access data base engine and return DataSet-cursor.  The technology is represented by two main component:  ...

    8-07-14_MegaCLI for linux_windows

    SCGCQ00352210 Defect MegaCli pdFwDownload fails on a SATA drive with an interposer SCGCQ00353584 Defect CLI has to refresh the MR_CTRL_INFO after the MR_DCMD_CTRL_FLASH_FW_DOWNLOAD for OFU. SCGCQ...

    EhLib 9.1.024

    or on the external source (updating parameters [Params] and requiring data from DataDriver). Allows once-only (without the dynamic support) sort data, including Calculated and Lookup field. ...

    EhLib 8.0 Build 8.0.023 Pro Edition FullSource for D7-XE8

    or on the external source (updating parameters [Params] and requiring data from DataDriver). Allows once-only (without the dynamic support) sort data, including Calculated and Lookup field. ...

    EhLib 6.3 Build 6.3.176 Russian version. Full source included.

    or on the external source (updating parameters [Params] and requiring data from DataDriver). Allows once-only (without the dynamic support) sort data, including Calculated and Lookup field. ...

    LCTF软件备份VariSpec™ Liquid Crystal Tunable Filters

    generates 搖nresolved external?at link-time Fixes/features added from previous release: b) added command VsEnableImplicitPalette() to code and documentation added command VsConnect() to code and ...

    EhLib5.0.13 最新的ehlib源码

    or on the external source (updating parameters [Params] and requiring data from DataDriver). Allows once-only (without the dynamic support) sort data, including Calculated and Lookup field. ...

Global site tag (gtag.js) - Google Analytics