【问题标题】:How to use ProcessBuilder when using redirection in Linux在 Linux 中使用重定向时如何使用 ProcessBuilder
【发布时间】:2016-06-12 03:12:24
【问题描述】:

我想使用 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)\""};

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

【问题讨论】:

  • 更新了我的问题。我想将几个 zcat 命令的输出重定向到排序。
  • ProcessBuilder 不是外壳。要么显式调用 shell,要么自己进行重定向。
  • 这不是重复的。这里的问题是不同的。我确实在第二次尝试中明确调用了 shell。
  • 首先,删除sort ... 周围的内部引号。其次,我不认为 sh 理解 &lt;(...) 语法 - 它更像是 bash 的东西。
  • 你是对的!我在发布问题几个小时后发现了这一点,但由于该问题被标记为重复,因此无法添加答案。

标签: java linux processbuilder


【解决方案1】:

我终于明白了。正如 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();

【讨论】:

  • 您使用了两次process.getInputStream()。第二个应该是错误流。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-01-26
  • 2017-05-27
  • 2023-03-22
  • 1970-01-01
  • 2013-03-07
  • 1970-01-01
相关资源
最近更新 更多