Execute an external program(转载)

本文介绍如何使用Java的Runtime类和ProcessBuilder类来执行外部程序,并捕获输出及错误级别。包括在不同操作系统中启动脚本文件、设置执行路径及参数等高级功能。

原文地址: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);

    }

}

General Information You can add external commands to each device on the map. E.g., execute the ping.exe utility or remote desktop, etc. In addition, the device parameters (like device address) will be entered automatically. This feature turns the Algorius Net Viewer into an effective tool for managing a computer network. Algorius Net Viewer contains large list of predefined external commands. Application makes a check at the first launch and enables only those commands which are available on a machine. You can hide, remove commands, or add a new command. Please, contact us if you need any additional external commands to be predefined. We are interested in it, and will try to add them in the next software version (for free). Configuring To configure external commands, select Commands→Configure from the device context menu. The Options window will appear: This window will allow you to add, edit, delete and group the external commands. You can also use available external commands as a basis for new one’s (external command duplicate option). There are built-in external commands which can’t be deleted or edited. They are located in Standard group by default. Checkbox next to external command of group of commands enables or disables its display in device context menu. You can drag an external command or group of commands with a mouse to another group. You can remove a command from a group in the same way. Pressing the Up (Ctrl+Up) or the Down →Ctrl+Down) buttons allows you to reorder external commands. Clicking the Add, Duplicate or Edit button will display the External Command window:
最新发布
03-20
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值