使用 Java ProcessBuilder 执行管道命令

编程入门 行业动态 更新时间:2024-10-28 04:23:43
本文介绍了使用 Java ProcessBuilder 执行管道命令的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我正在尝试使用 Java 的 ProcessBuilder 类来执行一个包含管道的命令.例如:

I'm trying to use Java's ProcessBuilder class to execute a command that has a pipe in it. For example:

ls -l | grep foo

但是,我收到一个错误:

However, I get an error:

ls: |: no such file or directory

关注:

ls: grep: no such file or directory

即使该命令从命令行完美运行,我也无法让 ProcessBuilder 执行将其输出重定向到另一个的命令.

Even though that command works perfectly from the command line, I can not get ProcessBuilder to execute a command that redirects its output to another.

有没有办法做到这一点?

Is there any way to accomplish this?

推荐答案

这应该有效:

ProcessBuilder b = new ProcessBuilder("/bin/sh", "-c", "ls -l| grep foo");

要执行管道,您必须调用一个 shell,然后在该 shell 中运行您的命令.

To execute a pipeline, you have to invoke a shell, and then run your commands inside that shell.

更多推荐

使用 Java ProcessBuilder 执行管道命令

本文发布于:2023-06-11 15:13:22,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/637435.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:管道   命令   Java   ProcessBuilder

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!