java - 在 Java 中通过管道将 Unix 命令组合在一起

标签 java unix piping

我需要从 Java 运行以下命令

echo <inputMessage> | iconv -f utf8 -t Cp930

当我使用下面的代码运行命令时,我看到只有 echo 部分被执行但管道没有发生

public static String callInconverter2(String input,String codePage) throws IOException {
        try{
        //  String command = "echo asdasdasd | iconv -f UTF-8 -t Cp930";
            Process p = Runtime.getRuntime().exec("echo "+input+"| iconv -f UTF-8 -t "+codePage);
        String s = null;
        BufferedReader stdInput = new BufferedReader(new 
                 InputStreamReader(p.getInputStream()));

            BufferedReader stdError = new BufferedReader(new 
                 InputStreamReader(p.getErrorStream()));
            StringBuilder sb = new StringBuilder();
            // read the output from the command
            System.out.println("Here is the standard output of the command:\n");
            while ((s = stdInput.readLine()) != null) {
                sb.append(s);
            }

            // read any errors from the attempted command
            System.out.println("Here is the standard error of the command (if any):\n");
            while ((s = stdError.readLine()) != null) {
                sb.append(s);
            }
            return sb.toString();

        }
        catch (IOException e) {
            System.out.println("exception happened - here's what I know: ");
            e.printStackTrace();
            return e.getMessage();
        }
            }}

我是 Runtime 的新手。有什么遗漏吗?

尝试了thomas建议的方法

String command = "echo asdasdasd | iconv -f UTF-8 -t Cp930";
Process p = Runtime.getRuntime().exec("bash -c \""+command+"\"");

asdasdasd: -c: line 0: unexpected EOF while looking for matching `"'asdasdasd: -c: line 1: syntax error: unexpected end of file 出现错误

有没有遗漏什么

最佳答案

运行 shell,使用该命令 -- bash、tcsh,无论您通常使用哪个。

bash -c "echo | iconv -f utf8 -t Cp930"                 // or
bash -lc "echo | iconv -f utf8 -t Cp930"

管道是一个 shell 功能。

因此:

Runtime rt = Runtime.getRuntime();
String cmd = "echo | iconv -f utf8 -t Cp930";
rt.exec("bash -c \""+cmd+"\"");

有关调用选项,请参阅 bash 手册。 http://www.gnu.org/software/bash/manual/html_node/Invoking-Bash.html#Invoking-Bash

关于java - 在 Java 中通过管道将 Unix 命令组合在一起,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16579789/

相关文章:

java - 如何使用 DOM 解析 java 中的内联/混合内容 xml 元素

unix - CPU 空闲百分比与平均负载

c - getopt(3) 如何工作, 'extern' 变量 optarg 是什么?

bash - 用户名/密码结构的BASH脚本

c - Windows CMD 中的管道不适用于用 C 编写的两个程序

c - C 中的无限管道

java - 使用 JavaFX 创建 webapp - 可能吗?

java 。 System.exit(int 状态)。退出状态值

java jzy3d依赖问题

c - 将一个命令 (execv) 的输出发送到另一个命令