从终端运行代码时会创建文本文件,但在Java中运行时则不会

时间:2012-05-21 10:02:09

标签: java linux

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)它的工作正常。

1 个答案:

答案 0 :(得分:0)

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

String [] cmd = {&#34; / bin / ksh&#34;,&#34; -c&#34;,&#34; yourcommand&lt; infile的&#34;};

Process process = Runtime.getRuntime()。exec(cmd);