从java运行.exe并继续

时间:2014-11-07 00:28:19

标签: java batch-file processbuilder

我想以编程方式运行.exe程序,如果它尚未运行。 目前我使用进程构建器从java启动.bat。批处理文件在检查它是否正在运行后运行.exe。 问题是java在用户关闭.exe程序之前不会继续前进。我该如何解决这个问题?

Java代码:

try {
        ProcessBuilder builder = new ProcessBuilder("open.bat");
        final Process process = builder.start();
        InputStream is = process.getInputStream();
        InputStreamReader isr = new InputStreamReader(is);
        BufferedReader br = new BufferedReader(isr);
        while ((br.readLine()) != null) {
        }
        System.out.println("command line terminated");
    } catch (Exception err) {
        err.printStackTrace();
        System.out.println("error  ");
    }

批次代码:(open.bat)

tasklist | find "illustrator.exe"
if errorlevel 1 start "" "C:\Program Files (x86)\Adobe\Adobe Illustrator CS6\Support Files\Contents\Windows\illustrator.exe"

1 个答案:

答案 0 :(得分:1)

<强>更新

使用...

start "" "C:\Program Files (x86)\Adobe\Adobe Illustrator CS4\Support Files\Contents\Windows\illustrator.exe"

作为open.bat批处理文件并使用...

try {
    ProcessBuilder builder = new ProcessBuilder("open.bat");
    builder.redirectError();
    builder.inheritIO();
    final Process process = builder.start();
    final InputStream is = process.getInputStream();
    InputStreamReader isr = new InputStreamReader(is);
    BufferedReader br = new BufferedReader(isr);
    String text = null;
    while ((text = br.readLine()) != null) {
        System.out.println(text);
    }

    System.out.println("command line terminated");
    System.out.println("Exited with " + process.waitFor());
} catch (Exception err) {
    err.printStackTrace();
    System.out.println("error  ");
}

我可以让批处理文件运行并终止,但仍然可以加载和运行Illustrator。

主要的添加是对ProcessBuilder#inheritIO的调用,这有些神奇我不知道,但似乎允许批处理文件终止......

来自JavaDocs

  

这使得行为等同于大多数操作系统命令解释程序或标准C库函数系统()。