Reputation: 791
I have a requirement to run the below command from Java
echo <inputMessage> | iconv -f utf8 -t Cp930
When i use the below code to run the command i see only the echo part is executed but the piping is not happening
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();
}
}}
I am new to Runtime. is there anything am missing.
Tried the method suggested by thomas
String command = "echo asdasdasd | iconv -f UTF-8 -t Cp930";
Process p = Runtime.getRuntime().exec("bash -c \""+command+"\"");
was getting an error asdasdasd: -c: line 0: unexpected EOF while looking for matching `"'asdasdasd: -c: line 1: syntax error: unexpected end of file
is there anything am missing out
Upvotes: 1
Views: 1635
Reputation: 14164
Run a shell, with that command -- bash, tcsh, whichever one you normally use.
bash -c "echo | iconv -f utf8 -t Cp930" // or
bash -lc "echo | iconv -f utf8 -t Cp930"
Piping is a shell functionality.
Thus:
Runtime rt = Runtime.getRuntime();
String cmd = "echo | iconv -f utf8 -t Cp930";
rt.exec("bash -c \""+cmd+"\"");
See the bash
manual for invocation options. http://www.gnu.org/software/bash/manual/html_node/Invoking-Bash.html#Invoking-Bash
Upvotes: 3