简体   繁体   English

从JAVA执行批处理文件并捕获批处理环境

[英]Execute batch files from JAVA and capture batch environment

I need a solution that allows to capture the batch file exit code and the resultant environment - by this I mean that I need to retrieve the system environment + variables set within the batch. 我需要一个可以捕获批处理文件退出代码和结果环境的解决方案-通过这种方式,我的意思是我需要检索批处理中设置的系统环境+变量。

For better understanding here is what I came up with. 为了更好地理解,这是我想到的。 Unfortunately the printEnvironment() method does not print out the variable MyVar set previously in batch but only the system variables. 不幸的是,printEnvironment()方法不会批量打印以前设置的变量MyVar,而只能打印系统变量。 Is there a way to capture "MyVar" without changeing the batch file itself? 是否可以在不更改批处理文件本身的情况下捕获“ MyVar”?

import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;

class Main{
    public static void main(String[] args){
        String command = "C:/temp/varTest.bat";

        MyTask mt = new MyTask(command);
        mt.run();
    }
}

class MyTask implements Runnable{       
    private ProcessBuilder pb;
    private Process process;
    private int exitCode;
    private Map<String, String> env;

    private String command;

    public MyTask(String command){
        this.command = command;
    }

    public void run(){
        try {
            pb = new ProcessBuilder(command);
            process = pb.start();

            process.waitFor();
            exitCode = process.exitValue();     

        } catch (IOException e) {
            e.printStackTrace();        
        } catch (InterruptedException e) {
            e.printStackTrace();
        }finally{
            System.out.println("Execution finished! Exit code: " + exitCode);

            printEnvironment();
            process.destroy();

        }           
    }

    private void printEnvironment(){
        env = pb.environment();

        List<String> envKeys = new ArrayList<String>(env.keySet());
        Collections.sort(envKeys);

        for(String key : envKeys){
            System.out.println(key+" ==> "+env.get(key));
        }
    }
}

The batch file code: 批处理文件代码:

set MyVar=VAL

before your code exits try doing this :- 在代码退出之前,尝试执行以下操作:-

Properties props = System.getProperties();
props.list(System.out);

I think I have found kind of a solution. 我想我找到了一种解决方案。 Not perfect but better than nothing. 不完美,但总比没有好。 To get the full environment left after batch execution I used different approach for fireing it up. 为了在批处理执行后留下完整的环境,我使用了不同的方法来启动它。

Simply I have started the batch in cmd which allowed me to pass additional commands as arguments. 简而言之,我已经在cmd中启动了该批处理,这使我可以传递其他命令作为参数。 Next I had to read the output from the output stream. 接下来,我必须从输出流中读取输出。 To my supprise I was also able to get the proper exit code from the batch - note though I had to use the clause: 令我惊讶的是,我还能够从批处理中获得正确的退出代码-注意,尽管我必须使用以下子句:

exit /B <exitCode> 

This are mods to the code above: 这是上面代码的mod:

pb = new ProcessBuilder("cmd.exe", "/c", command, "&&set", "&&exit");
process = pb.start();       
pb.redirectErrorStream(true);

process.waitFor();
exitCode = process.exitValue();

stdout = process.getInputStream ();
stdOutReader = new BufferedReader (new InputStreamReader(stdout));

... ...

String outLine;

while ((outLine = stdOutReader.readLine ()) != null) {
    if(outLine.trim().length() > 0){
        System.out.println ("OUT STREAM: " + outLine);
    }    
}

Any comments and alternate solutions are most welcome. 任何意见和替代解决方案都是最欢迎的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM