echo "text" > /home/maxbester/test.txt
Java プログラムで、いくつかの Unix ベースのシステムでコマンドを実行したいと考えています。
私のコードは次のようになります:
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 が存在する場合、 res には"text" > /home/maxbester/test.txt
( ではなくecho "text" > /home/maxbester/test.txt
、エコーが消えて) が含まれ、test.txt は空になります。ただし、終了値は 0 です (したがって、正しく機能するはずです)。
私は手動で実行しecho "text" > /home/maxbester/test.txt
ます。何も返されず、終了値も 0 でした。
では、exec コマンドの何が問題になっているのでしょうか。