Reputation: 219
I have a command to run on Terminal OSX:
cat File1 | ./huawei2text.pl > ~/File2.txt && cat ~/File2.txt| tr "," "\n" > ~/Output.txt
How can I run this command using only java?
I tried this code:
String whatToRun = "cat File1 | ./File.pl > ~/File2.txt && cat ~/File2.txt| tr "," "\n" > ~/Output.txt";
try
{
Runtime rt = Runtime.getRuntime();
Process proc = rt.exec(whatToRun);
int exitVal = proc.waitFor();
System.out.println("Process exitValue:" + exitVal);
} catch (Throwable t)
{
t.printStackTrace();
}
Updated
Answer and solution:
String whatToRun = "cat File1 | ./File.pl > File2.txt "
+ "&& cat File2.txt| tr \",\" \"\n\" > Output.txt";
String[] shellcmd = {"/bin/sh", "-c", whatToRun};
try {
Runtime rt = Runtime.getRuntime();
Process proc = rt.exec(shellcmd);
int exitVal = proc.waitFor();
System.out.println("Process exitValue:" + exitVal);
}
catch (Throwable t) {
t.printStackTrace();
}
Now It works. Thank you!
Upvotes: 0
Views: 1202
Reputation: 123508
Pipes would be interpreted by the shell. Ask your shell to execute the command instead:
String[] shellcmd = {
"/bin/sh",
"-c",
whatToRun
};
Process proc = rt.exec(shellcmd);
Upvotes: 2
Reputation: 200168
The Java API allows you to start one subprocess, by naming an executable to run. What you have there is a whole mini-script banged together into a one-liner. Only a shell can interpret such things, so your string should start with something like
/bin/sh -c '... your command ...'
Note the single quotes, they are important.
Upvotes: 0