【问题标题】:Text file is created when running code from the terminal, but not when running it in Java从终端运行代码时会创建文本文件,但在 Java 中运行时不会
【发布时间】:2012-05-21 10:02:09
【问题描述】:
public static void main(String[] args) throws Exception {
  System.setOut(new PrintStream(
      new FileOutputStream("/home/main/smt/output/out.txt")));

  try {
    String line;
    Process p = Runtime.getRuntime().exec(
        "/home/main/smt/tools/moses-2010-08-13/moses/moses-cmd/src/moses " +
        "-f /home/main/smt/work/model/moses.ini " +
        "< /home/main/smt/work/corpus/dataset.en" );

    BufferedReader in = new BufferedReader(
                   new InputStreamReader(p.getInputStream()) );
    while ((line = in.readLine()) != null) {
      System.out.println(line);
    }
    in.close();
  }
  catch (Exception e) {
    // ...
  }
}

命令

home/main/smt/tools/moses-2010-08-13/moses/moses-cmd/src/moses 
  -f /home/main/smt/work/model/moses.ini
  < /home/main/smt/work/corpus/dataset.en
  >/home/main/smt/output/out.txt

在 Linux 的终端中执行并创建 out.txt。但在 java 中没有创建 out.txt

dataset.en 是输入文件。使用模型中srcmoses.ini 中的exe moses,dataset.en 中的内容被翻译并保存在out.txt 中。 但是在运行此代码时,这里没有创建 out.txt。尽管控制台中没有显示任何内容,但我从命令中删除了将输出保存在文件中。如果我更改 Process p = Runtime.getRuntime().exec(ls) 它工作正常。

【问题讨论】:

  • 重定向运算符,如&lt;&gt; 是shell 的一部分,不能直接与Runtime.exec() 一起使用。选项见this SO thread

标签: java linux


【解决方案1】:

Shell 可以解释重定向和参数。你应该尝试

String[] cmd = {"/bin/ksh", "-c", "你的命令

进程进程 = Runtime.getRuntime().exec(cmd);

【讨论】:

    猜你喜欢
    • 2018-12-21
    • 1970-01-01
    • 1970-01-01
    • 2018-07-09
    • 1970-01-01
    • 2021-08-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多