我需要一个允许捕获批处理文件退出代码和结果环境的解决方案 - 我的意思是我需要检索批处理中设置的系统环境+变量。
为了更好地理解这里是我想出的。不幸的是,printEnvironment() 方法不会打印出之前批量设置的变量 MyVar,而只会打印出系统变量。有没有办法在不更改批处理文件本身的情况下捕获“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));
}
}
}
批处理文件代码:
set MyVar=VAL