我需要从 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/