0

echo "text" > /home/maxbester/test.txtJava プログラムで、いくつかの 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 コマンドの何が問題になっているのでしょうか。

4

2 に答える 2

0

exec をシェルのように動作させたい場合は、シェルを呼び出す必要があります。例えば

String shell = System.getEnv("SHELL");
cmd = shell + " -c \"echo test > /home/maxbester/test\"";

あなたのテストは stderr を読みません。そこに面白いものがあったのかもしれません。

于 2012-10-12T11:31:44.000 に答える
0

Java でファイルにテキストを書き込みたい場合は、ストリームのリダイレクトなどのシェル固有の詳細に頼るのではなく、FileWriterを検討する必要があります。

于 2012-10-12T11:28:32.617 に答える