我要做的只是运行一个批处理文件,该文件执行后续命令成功执行所需的一些准备工作(设置环境变量和内容)。为了证明这一点,我整理了一个使用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();
}
}
}
但是打印空字符串而不是单词“test”。有线索吗?
答案 0 :(得分:0)
根据其他论坛的反馈回答我自己的问题。诀窍是在每个命令的末尾添加一个新的行字符,如下所示:
os.write("export MY_VAR=test\n");
os.flush();
os.write("echo $MY_VAR\n");