0

可能是这个问题太简单了,但我花了很多时间,但我无法弄清楚。我正在尝试执行echo我试图在文本文件中附加一些数据的命令。在终端中运行时一切正常,但是当我尝试通过它运行时Runtime.getRuntime().exec("echo my text >> file.txt"),>> 不起作用。

有什么方法可以提供代码或其他东西以便这个命令可以工作吗?我试过>了,但它对我不起作用。

4

1 回答 1

0

问题是:应该在哪个 shell 中执行 echo 命令?Runtime.exec 可以得到一个 cmdArray。http://docs.oracle.com/javase/7/docs/api/java/lang/Runtime.html#exec%28java.lang.String[],%20java.lang.String[]%29

import java.io.*;

class RuntimeExecLinux {
  public static void main(String[] args){
      try {
        // Execute a command with arguments
        String[] cmd = new String[]{"/bin/bash", "-c", "echo 'my text from java' >> file.txt"};
        Process child = Runtime.getRuntime().exec(cmd);

        cmd = new String[]{"/bin/bash", "-c", "cat file.txt"};
        child = Runtime.getRuntime().exec(cmd);

        // Get the input stream and read from it
        InputStream in = child.getInputStream();
        int c;
        while ((c = in.read()) != -1) {
            System.out.print((char)c);
        }
        in.close();

      } catch (IOException e) {
        e.printStackTrace();
      }
  }
}

问候

阿克塞尔

于 2014-08-24T12:47:40.893 回答