我想讓我的Java程序在幾個基於Unix的系統上運行命令echo "text" > /home/maxbester/test.txt
。Java - exec的行爲不像shell
我的代碼如下所示:
private static final Logger LOG = Logger.getLogger(MyClass.class);
public String run(String cmd) {
String res = null;
InputStream is = null;
try {
final Runtime rt = Runtime.getRuntime();
final Process p = rt.exec(cmd);
int exitStatus = -1;
try {
exitStatus = p.waitFor();
} catch (InterruptedException e) {
L0G.error(e.getMessage(), e);
}
is = p.getInputStream();
if (exitStatus == 0) {
if (is != null && is.available() > 0) {
StringWriter stringWriter = new StringWriter();
IOUtils.copy(is, stringWriter);
res = stringWriter.toString();
} else {
L0G.error("InputStream is not available!");
}
}
} catch (SecurityException e) {
L0G.error(e.getMessage(), e);
} catch (IOException e) {
L0G.error(e.getMessage(), e);
}
return res;
}
在CMD等於echo "text" > /home/maxbester/test.txt
和文件test.txt存在,資源包含"text" > /home/maxbester/test.txt
(而不是echo "text" > /home/maxbester/test.txt
,該呼應 disapeared)和test.txt的是空的。但是,出口值是0(所以它應該正常工作)。
我手動運行echo "text" > /home/maxbester/test.txt
。什麼都沒有返回,退出值也是0.
那麼exec命令出了什麼問題?
事實是,在某種模式下,程序使用JSch在遠程機器上完成工作。所以我只能使用'setCommand'方法來完成這項工作。我想有一個類似的行爲。 – Maxbester