/Users/lyon/j4p/src/bookExamples/ch16Readers/ExecDemo.java

1    package bookExamples.ch16Readers; 
2     
3    import java.io.BufferedReader; 
4    import java.io.IOException; 
5    import java.io.InputStream; 
6    import java.io.InputStreamReader; 
7    import java.util.ArrayList; 
8     
9    public class ExecDemo { 
10       static public String[] runCommand(String cmd) 
11               throws IOException { 
12           // set up list to capture command output lines 
13    
14           ArrayList list = new ArrayList(); 
15    
16           // start command running 
17    
18           Process proc = Runtime.getRuntime().exec(cmd); 
19    
20           // get command's output stream and 
21           // put a buffered reader input stream on it 
22    
23           InputStream istr = proc.getInputStream(); 
24           BufferedReader br = 
25                   new BufferedReader(new InputStreamReader(istr)); 
26    
27           // read output lines from command 
28    
29           String str; 
30           while ((str = br.readLine()) != null) 
31               list.add(str); 
32    
33           // wait for command to terminate 
34    
35           try { 
36               proc.waitFor(); 
37           } catch (InterruptedException e) { 
38               System.err.println("process was interrupted"); 
39           } 
40    
41           // check its exit value 
42    
43           if (proc.exitValue() != 0) 
44               System.err.println("exit value was non-zero"); 
45    
46           // close stream 
47    
48           br.close(); 
49    
50           // return list of strings to caller 
51    
52           return (String[]) list.toArray(new String[0]); 
53       } 
54    
55       public static void main(String args[]) { 
56           try { 
57               // run a command 
58    
59               String outlist[] = runCommand("test"); 
60    
61               // display its output 
62    
63               for (int i = 0; i < outlist.length; i++) 
64                   System.out.println(outlist[i]); 
65           } catch (IOException e) { 
66               System.err.println(e); 
67           } 
68       } 
69   } 
70