Friday, February 3, 2012

Runtime.getRuntime().exec with Output Redirection

Runtime.getRuntime().exec is a method used in Java to execute internal command of the operating system. The use of the method is quite straightforward, for example the code to display a content of a current directory (the "ls" command) is shown as follow:

1:  import java.io.*;  
2:  public class TestExec {  
3:    public static void main(String[] args) {  
4:      try {  
5:        Process p = Runtime.getRuntime().exec("ls");  
6:        BufferedReader in = new BufferedReader(  
7:                  new InputStreamReader(p.getInputStream()));  
8:        String line = null;  
9:        while ((line = in.readLine()) != null) {  
10:          System.out.println(line);  
11:        }  
12:      } catch (IOException e) {  
13:        e.printStackTrace();  
14:      }  
15:    }  
16:  }  

However, the above code will not works to execute more "complex" command, for example when piping or output redirection is involved. For example, the command "cat * > total" will not be executed. Therefore, for the piping or output redirection command to be involved, the above code will be changed as follow:

1:  import java.io.*;  
2:  public class TestExec {  
3:    public static void main(String[] args) {  
4:      try {  
5:        String[] complexCommand = {"/bin/bash", "-c", "cat * > total"};  
6:        Process p = Runtime.getRuntime().exec(complexCommand);  
7:        BufferedReader in = new BufferedReader(  
8:                  new InputStreamReader(p.getInputStream()));  
9:        String line = null;  
10:        while ((line = in.readLine()) != null) {  
11:          System.out.println(line);  
12:        }  
13:      } catch (IOException e) {  
14:        e.printStackTrace();  
15:      }  
16:    }  
17:  }  

I hope this piece of code could be useful for you :)

-gandhi

No comments:

Post a Comment