Java调用外部程序实例(windows批处理篇)
来源:互联网 发布:《算法》第4版是java吗 编辑:程序博客网 时间:2024/05/16 01:16
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批处理篇)
- Java调用批处理程序
- java调用外部程序
- Java调用外部程序
- Java调用外部程序
- java调用外部程序
- Java调用外部程序
- JAVA 调用外部程序
- Java调用外部程序
- Java 调用外部程序
- Windows API调用外部程序
- Windows API调用外部程序
- Windows API调用外部程序
- Java程序调用CMD批处理
- java调用外部程序执行
- java实现外部程序调用
- 使用Java调用外部程序
- Java调用外部程序命令
- Confusion, diffusion, Collision, Substitution
- 记下自己一直比较模糊的东西(2)
- How to configuratie the Windows Mobile DLL debug environment
- C关于指针和内存的那些大事
- 构建 Eclipse 插件在 EMF 模型中浏览内容
- Java调用外部程序实例(windows批处理篇)
- 用 Eclipse Modeling Framework 实现模型驱动开发,第 1 部分
- js压缩方法
- Linux的shell编程(二)
- 使用JInternalFrame实现MDI
- SQL2005各版本比较
- 计算机专业就业方向
- jcaptcha做jsp彩色验证码
- 对JXL包的研究(java操作excel)