javaterminalubuntu-13.04

Alternate to print greater than (>) symbol in Ubuntu


May be this question is too easy but it took a lot my time but I could not figure out. I am trying to execute echo command in which I am trying to append some data in a text file. Everything works when run in terminal but when I try to run it through Runtime.getRuntime().exec("echo my text >> file.txt"), then >> does not work.

Is there any way to give code or something so that this command should work? I tried > but it did not work for me.


Solution

  • The problem is: In which shell should the echo command be executed? Runtime.exec can get a cmdArray. http://docs.oracle.com/javase/7/docs/api/java/lang/Runtime.html#exec%28java.lang.String[],%20java.lang.String[]%29

    import java.io.*;
    
    class RuntimeExecLinux {
      public static void main(String[] args){
          try {
            // Execute a command with arguments
            String[] cmd = new String[]{"/bin/bash", "-c", "echo 'my text from java' >> file.txt"};
            Process child = Runtime.getRuntime().exec(cmd);
    
            cmd = new String[]{"/bin/bash", "-c", "cat file.txt"};
            child = Runtime.getRuntime().exec(cmd);
    
            // Get the input stream and read from it
            InputStream in = child.getInputStream();
            int c;
            while ((c = in.read()) != -1) {
                System.out.print((char)c);
            }
            in.close();
    
          } catch (IOException e) {
            e.printStackTrace();
          }
      }
    }
    

    Greetings

    Axel