progfan
progfan

Reputation: 2526

Running a bash command from within a Java program

Consider a piece of Java code:

import java.io.IOException;
public class Demo{
          public static void main(String []args) throws IOException{
                   ...
                   String abc="i am here";
                   System.out.println(abc);
 }

}

I want to run - echo "THIS IS STUFF FOR THE FILE" >> file1.txt - immediately after the System.out.println() line, assuming file1.txt is in the same directory.

Upvotes: 0

Views: 2661

Answers (2)

hellerve
hellerve

Reputation: 508

Use the Runtime.getRuntime().exec() command like so:

Runtime.getRuntime().exec("echo 'THIS IS STUFF FOR THE FILE!' > file1.txt");

The documentation can be read here.

If it's not working or you find the command handy and want to know more about it, do yourself a favour and read this. It will save you sweat.

Upvotes: -1

Eric Jablow
Eric Jablow

Reputation: 7899

The ProcessBuilder class is the more modern version.

import static java.lang.ProcessBuilder.Redirect.appendTo;

ProcessBuilder pb = new ProcessBuilder("/bin/echo", "THIS IS STUFF FOR THE FILE");
pb.redirectOutput(appendTo(new File("file1.txt")));
Process p = pb.start();

Notice that this calls /bin/echo directly instead of having bash look through the PATH. That's safer, as there is no chance of getting a hacked echo. Also, since this doesn't use bash, Java is used to redirect the output.

Upvotes: 3

Related Questions