0
我有一個問題,用r.exec調用一些簡單的命令行函數 - 出於某種原因,給定一個文件X命令 'echo完整/路徑/到/ X'工作正常(在顯示和'p.exitValue()== 0',但'貓滿/路徑/到/ X'不(並具有'p.exitValue() == 1') - 'cat'和'echo'都位於/ bin /我的OSX上 - 我是否缺少某些東西?代碼在下面(因爲它發生了,任何改善代碼的建議都會受到歡迎...)Runtime.exec - 適用於'echo''但不適用於貓...
private String takeCommand(Runtime r, String command) throws IOException {
String returnValue;
System.out.println("We are given the command" + command);
Process p = r.exec(command.split(" "));
InputStream in = p.getInputStream();
BufferedInputStream buf = new BufferedInputStream(in);
InputStreamReader inread = new InputStreamReader(buf);
BufferedReader bufferedreader = new BufferedReader(inread);
// Read the ls output
String line;
returnValue = "";
while ((line = bufferedreader.readLine()) != null) {
System.out.println(line);
returnValue = returnValue + line;
}
try {// Check for failure
if (p.waitFor() != 0) {
System.out.println("XXXXexit value = " + p.exitValue());
}
} catch (InterruptedException e) {
System.err.println(e);
} finally {
// Close the InputStream
bufferedreader.close();
inread.close();
buf.close();
in.close();
}
try {// should slow this down a little
p.waitFor();
} catch (InterruptedException e) {
e.printStackTrace();
}
return returnValue;
}
如果您使用ProcessBuilder,則可以將stdout和stderr結合使用,以便只有一個流可以讀取。 – 2012-08-13 10:36:25