public Process exec(String command);
public Process exec(String [] cmdArray);
public Process exec(String command, String [] envp);
public Process exec(String [] cmdArray, String [] envp);
java调用外部程序主要使用上述4个函数,具体用法可以查看API文档说明。以下代码在jdk1.5版经过测试通过。
java代码:
- import java.io.BufferedReader;
- import java.io.IOException;
- import java.io.InputStream;
- import java.io.InputStreamReader;
- public class WindowsExec {
- public static void main(String args[]) {
- if (args.length < 1) {
- System.out.println("USAGE: java WindowsExec <cmd>");
- System.exit(1);
- }
- try {
- String osName = System.getProperty("os.name");
- String[] cmd = new String[4];
- System.out.println(osName);
- if (osName.equals("Windows XP")) {
- cmd[0] = "cmd.exe";
- cmd[1] = "/C";
- cmd[2] = args[0]; // *.bat
- cmd[3] = "20080612";// parameter
- } else {
- //unix
- }
- Runtime rt = Runtime.getRuntime();
- System.out.println("Execing " + cmd[0] + " " + cmd[1] + " "+ cmd[2] + cmd[3]);
- Process proc = rt.exec(cmd);
- // get error stream
- StreamGobbler errorGobbler
- = new StreamGobbler(proc.getErrorStream(), "ERROR");
- // get input stream
- StreamGobbler outputGobbler
- = new StreamGobbler(proc.getInputStream(), "OUTPUT");
- // output msg
- errorGobbler.start();
- outputGobbler.start();
- // return value
- int exitVal = proc.exitValue();
- System.out.println("ExitValue: " + exitVal);
- } catch (Throwable t) {
- t.printStackTrace();
- }
- }
- }
- class StreamGobbler extends Thread {
- InputStream is;
- String type;
- StreamGobbler(InputStream is, String type) {
- this.is = is;
- this.type = type;
- }
- public void run() {
- try {
- InputStreamReader isr = new InputStreamReader(is);
- BufferedReader br = new BufferedReader(isr);
- String line = null;
- while ((line = br.readLine()) != null){
- System.out.println(type + ">" + line);
- }
- } catch (IOException ioe) {
- ioe.printStackTrace();
- }
- }
- }
batch代码:
- echo off
- set PATH=%JAVA_HOME%bin;%PATH%
- d:
- set basedir=D:/batch
- echo 批处理: %1
- java -jar %basedir%/batch.jar %1
- IF ERRORLEVEL 1 goto ERROR_EXIT
- echo ***** 正常終了 *****
- EXIT 0
- :ERROR_EXIT
- echo ***** 发生错误 *****
- EXIT 1
完~
Java调用外部程序实例(windows批处理篇)
最新推荐文章于 2024-09-15 19:46:31 发布