0

我有一个要在终端 OSX 上运行的命令:

cat File1 | ./huawei2text.pl > ~/File2.txt && cat ~/File2.txt| tr "," "\n"  > ~/Output.txt

如何仅使用 java 运行此命令?

我试过这段代码:

String whatToRun = "cat File1 | ./File.pl > ~/File2.txt && cat ~/File2.txt| tr "," "\n"  > ~/Output.txt";
   try
   {
     Runtime rt = Runtime.getRuntime();
     Process proc = rt.exec(whatToRun);
     int exitVal = proc.waitFor();
     System.out.println("Process exitValue:" + exitVal);
   } catch (Throwable t)
     {
       t.printStackTrace();
     }

更新

答案和解决方案:

String whatToRun = "cat File1 | ./File.pl > File2.txt "
            + "&& cat File2.txt| tr \",\" \"\n\"  > Output.txt";
String[] shellcmd = {"/bin/sh", "-c", whatToRun};

try {
    Runtime rt = Runtime.getRuntime();
    Process proc = rt.exec(shellcmd);
    int exitVal = proc.waitFor();
    System.out.println("Process exitValue:" + exitVal);
    }
catch (Throwable t) {
    t.printStackTrace();
}

现在它起作用了。谢谢!

4

2 回答 2

2

管道将由shell解释。让您的 shell 改为执行命令:

String[] shellcmd = {
  "/bin/sh",
  "-c",
  whatToRun
};

Process proc = rt.exec(shellcmd);
于 2013-08-19T11:01:57.083 回答
0

Java API 允许您通过命名要运行的可执行文件来启动一个子进程。你所拥有的是一个完整的迷你脚本组合成一个单行。只有 shell 可以解释这样的事情,所以你的字符串应该以类似的开头

/bin/sh -c '... your command ...'

注意单引号,它们很重要。

于 2013-08-19T11:00:42.010 回答