diddyrock 发表于 2013-2-4 19:48:48

java process

此博估计唯一一个完整可编译的代码哈哈

import java.io.*;
import java.util.*;

//Commons Logging imports
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;


public class TestProcess{

public static final Log LOG = LogFactory.getLog(TestProcess.class);

    public static int doWaitFor(Process p) {
       int exitValue = -1; // returned to caller when p is finished
       try {
   
            InputStream in = p.getInputStream();
            InputStream err = p.getErrorStream();
            boolean finished = false; // Set to true when p is finished
      
            while(!finished); {
               try {
                   while( in.available() > 0) {
                     // Print the output of our system call
                     Character c = new Character( (char) in.read());
                     System.out.print( c);
                   }
                   while( err.available() > 0) {
                     // Print the output of our system call
                     Character c = new Character( (char) err.read());
                     System.out.print( c);
                   }
   
                   // Ask the process for its exitValue. If the process
                   // is not finished, an IllegalThreadStateException
                   // is thrown. If it is finished, we fall through and
                   // the variable finished is set to true.
                   exitValue = p.exitValue();
                  finished = true;
               }
               catch (IllegalThreadStateException e) {
                   // Process is not finished yet;
                   // Sleep a little to save on CPU cycles
                   Thread.currentThread().sleep(500);
               }
         }
       }
       catch (Exception e) {
         // unexpected exception! print it out for debugging...
          System.err.println( "doWaitFor();: unexpected exception - " +
         e.getMessage());
       }
   
       // return completion status to caller
       return exitValue;
}



public static void main(String args[]){



String[] cmd = {"/temp/single.sh","656.gif"};
File directory = new File("/temp/");

ProcessBuilder pb = new ProcessBuilder(cmd);

pb.directory(directory);
Map<String,String> map = pb.environment();
pb.redirectErrorStream(true);
try{
Process process = pb.start();
int exit = process.waitFor();
//int exit = TestProcess.doWaitFor(process);
System.out.println(exit);
}catch(Exception e){
e.printStackTrace();
}


}
}
页: [1]
查看完整版本: java process