I want my Java program to run the command echo "text" > /home/maxbester/test.txt on several Unix based systems.
My code looks like:
private static final Logger LOG = Logger.getLogger(MyClass.class);
public String run(String cmd) {
String res = null;
InputStream is = null;
try {
final Runtime rt = Runtime.getRuntime();
final Process p = rt.exec(cmd);
int exitStatus = -1;
try {
exitStatus = p.waitFor();
} catch (InterruptedException e) {
L0G.error(e.getMessage(), e);
}
is = p.getInputStream();
if (exitStatus == 0) {
if (is != null && is.available() > 0) {
StringWriter stringWriter = new StringWriter();
IOUtils.copy(is, stringWriter);
res = stringWriter.toString();
} else {
L0G.error("InputStream is not available!");
}
}
} catch (SecurityException e) {
L0G.error(e.getMessage(), e);
} catch (IOException e) {
L0G.error(e.getMessage(), e);
}
return res;
}
When cmd equals echo "text" > /home/maxbester/test.txt and the file test.txt exists, res contains "text" > /home/maxbester/test.txt (and not echo "text" > /home/maxbester/test.txt, the echo disapeared) and test.txt is empty. However the exit value is 0 (so it should have worked correctly).
I run manually echo "text" > /home/maxbester/test.txt. Nothing was returned and the exit value was also 0.
So what’s going wrong with the exec command?
If you want to write text to a file in Java, you should take a look at FileWriter instead of relying on shell-specific details such as stream redirection.