java - 在 Linux 中使用重定向时如何使用 ProcessBuilder

标签 java linux processbuilder

我想使用 ProcessBuilder 运行此命令:

sort -m -u -T /dir -o output <(zcat big-zipped-file1.gz | sort -u) <(zcat big-zipped-file2.gz | sort -u) <(zcat big-zipped-file3.gz | sort -u) 

我尝试了以下方法:

// This doesn't recognise the redirection.
String[] args = new String[] {"sort", "-m", "-u", "-T", "/dir", "-o", "output", "<(zcat big-zipped-file1.gz | sort -u)", "<(zcat big-zipped-file2.gz | sort -u)", "<(zcat big-zipped-file3.gz | sort -u)"};

// This gives:
// /bin/sh: -c: line 0: syntax error near unexpected token `('
String[] args = new String[] {"/bin/sh", "-c", "\"sort -m -u -T /dir -o output <(zcat big-zipped-file1.gz | sort -u) <(zcat big-zipped-file2.gz | sort -u) <(zcat big-zipped-file3.gz | sort -u)\""};

我正在像这样使用 args:processBuilder.command(args);

最佳答案

我终于明白了。正如 Roman 在他的评论中提到的,sh 不理解重定向,所以我不得不使用 bash。我还必须同时使用输入流和错误流。

String[] args = new String[] {"/bin/bash", "-c", "sort -m -u -T /dir -o output <(zcat big-zipped-file1.gz | sort -u) <(zcat big-zipped-file2.gz | sort -u) <(zcat big-zipped-file3.gz | sort -u)"};

ProcessBuilder builder = new ProcessBuilder();
builder.command(args);
Process process = builder.start();
BufferedReader input = new BufferedReader(new InputStreamReader(process.getInputStream()));
BufferedReader error = new BufferedReader(new InputStreamReader(process.getErrorStream()));
while((line = input.readLine()) != null);
while((line = error.readLine()) != null);

process.waitFor();

关于java - 在 Linux 中使用重定向时如何使用 ProcessBuilder,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37770383/

相关文章:

java - 以编程方式解决数独

linux - iPhone : Local DNS for local domains - cellular data for external addresses

c++ - 按名称获取进程 ID

shell - 使用java执行shell脚本时出现语法错误

Java ProcessBuilder

java - ProcessBuilder(Java)-创建cronjob

java - 什么 Maven Artefact 持有 PowerMock.mockStaticPartial?

java - API Spring boot 自动重定向到登录页面

java - Spring MVC Struts 混合

c++ - 错误: "Undefined reference to ' main'"