`
linsl
  • 浏览: 70641 次
  • 性别: 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 ...

    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 ...

    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:  ...

    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. ...

    ehlib_vcl_src_9_3.26

    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. ...

    javacv-platform-1.3.3-src

    JavaCV also comes with hardware accelerated full-screen image display (CanvasFrame and GLCanvasFrame), easy-to-use methods to execute code in parallel on multiple cores (Parallel), user-friendly ...

    Bochs - The cross platform IA-32 (x86) emulator

    specify an alternative redolog file of USB MSD disk image modes) - hard drive - new disk image mode 'vvfat' - ported the read-only part of Qemu's 'virtual VFAT' block driver - additions: ...

    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...

    pro_apache_third_edition..pdf

    Contents About the Author...............................................................................................xix About the Technical Reviewer and Contributing Author.................xxi ...

Global site tag (gtag.js) - Google Analytics