我需要从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的新手。有没有什么遗失。
尝试了托马斯建议的方法
String command = "echo asdasdasd | iconv -f UTF-8 -t Cp930";
Process p = Runtime.getRuntime().exec("bash -c \""+command+"\"");
收到错误asdasdasd:-c:第0行:意外的EOF,同时寻找匹配的“”'asdasdasd:-c:第1行:语法错误:意外的文件结束
有什么遗漏
答案 0 :(得分:3)
使用该命令运行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