使用Java运行在Mac上使用终端管道的命令

时间:2013-08-19 10:53:27

标签: java macos shell terminal

我有一个在终端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();
}

现在它有效。谢谢!

2 个答案:

答案 0 :(得分:2)

管道将由 shell 解释。请求shell执行命令:

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

Process proc = rt.exec(shellcmd);

答案 1 :(得分:0)

Java API允许您通过命名要运行的可执行文件来启动一个子进程。你在那里有一个完整的迷你脚本撞在一起。只有shell才能解释这些内容,所以你的字符串应该以

之类的东西开头
/bin/sh -c '... your command ...'

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