1
我想要做的只是運行一個批處理文件,爲後續命令成功執行(設置環境變量和內容)做必要的準備工作。爲了證明這一點,我放在一起使用Commons Exec的使用Commons Exec進行上下文敏感執行
public class Tester {
public static void main(String[] args) throws Exception {
Tester tester = new Tester();
MyResultHandler handler = tester.new MyResultHandler();
CommandLine commandLine = CommandLine.parse("bash");
PipedOutputStream ps = new PipedOutputStream();
PipedInputStream is = new PipedInputStream(ps);
BufferedWriter os = new BufferedWriter(new OutputStreamWriter(ps));
Executor executor = new DefaultExecutor();
PumpStreamHandler ioh = new PumpStreamHandler(System.out, System.err, is);
executor.setStreamHandler(ioh);
ioh.start();
executor.execute(commandLine, handler);
os.write("export MY_VAR=test");
os.flush();
os.write("echo $MY_VAR");
os.flush();
os.close();
}
private class MyResultHandler extends DefaultExecuteResultHandler {
@Override
public void onProcessComplete(final int exitValue) {
super.onProcessComplete(exitValue);
System.out.println("\nsuccess");
}
@Override
public void onProcessFailed(final ExecuteException e) {
super.onProcessFailed(e);
e.printStackTrace();
}
}
}
樣品,不過,打印空字符串,而不是「測試」一詞。任何線索?