~/-6ren">
gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 06:48:39 29 4
gpt4 key购买 nike

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

现在可以了。谢谢!

最佳答案

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

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

Process proc = rt.exec(shellcmd);

关于java - 使用 Java 在 Mac 上的终端中运行使用管道的命令,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18312034/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com