1

我需要从 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();
        }
            }}

我是运行时的新手。有什么遗漏吗?

尝试了托马斯建议的方法

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

有什么遗漏的吗

4

1 回答 1

3

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

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

管道是一个外壳功能。

因此:

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

于 2013-05-16T05:48:48.383 回答