0

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.

progfan
  • 2,454
  • 3
  • 22
  • 28
  • 1
    And what have you tried so far? – fge May 29 '13 at 22:32
  • 1
    And why do you want to do this? What does bash give you that Java IO does not? – Eric Jablow May 29 '13 at 22:33
  • Using Runtime as seen in http://stackoverflow.com/questions/8496494/running-command-line-in-java may be the answer. – DNax May 29 '13 at 22:34
  • http://stackoverflow.com/questions/615948/how-do-i-run-a-batch-file-from-my-java-application <- That is Batch, but basically the same – hellerve May 29 '13 at 22:34
  • I tried to do command.add(). But it didn't seem to work. I last worked on java many years ago and I am having to go through a Java source code intermittently. I am able to do certain minor things better using bash, currently. – progfan May 29 '13 at 23:23

2 Answers2

3

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.

Eric Jablow
  • 7,874
  • 2
  • 22
  • 29
  • Thanks a lot, Eric. That looks clinical. I will try this out and get back to you as soon as possible. – progfan May 29 '13 at 23:25
  • Re: "instead of having `bash` look through the `PATH`", "a hacked `echo`": `echo` is actually built into Bash, so these are not concerns. One could actually argue that it's safer to use the Bash builtin than to use `/bin/echo`, since the former will behave the same way on every system with Bash, whereas the latter's behavior is more variable. (Of course, the former depends on the presence of Bash, whereas the latter does not.) – ruakh May 29 '13 at 23:34
  • I hadn't realized that `echo` was built into `bash`. I'm just a bit paranoid about shell scripting in general. – Eric Jablow May 29 '13 at 23:38
-1

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.

dan1st
  • 12,568
  • 8
  • 34
  • 67
hellerve
  • 508
  • 1
  • 6
  • 30