Skip to content

Files

Latest commit

0840bc8 · Feb 28, 2017

History

History
75 lines (58 loc) · 1.84 KB

java-external-process.adoc

File metadata and controls

75 lines (58 loc) · 1.84 KB

When Runtime.exec() won’t

Java Pitfalls: Excuting an external program using Runtime.exec() method or ProcessBuilder class

예제

public class StreamConverter implements Runnable {

 private StringBuilder message =null;
 private InputStream input = null;
 public StreamConverter(InputStream input){
  this.input = input;
  this.message = new StringBuilder();
 }

 public void run() {
    BufferedReader reader = new BufferedReader(new InputStreamReader(input));
    String line= null;
    try {
   while( (line = reader.readLine())!=null){
      message.append(line);
     }
    } catch (IOException e) {
    throw new IllegalStateException("cann not read stream",e);
    }
 }

 public StringBuilder getMessage() {
  return message;
 }
}
waitFor는 무한대기 될 수도 있다…​
public static void main(String[] args) throws IOException, InterruptedException{
        Process pc = Runtime.getRuntime().exec("java");
        InputStream input = pc.getInputStream();
        IOUtils.copy(input, System.out);
        int exitCode = pc.waitFor();
        System.out.println(exitCode);
 }
멈추는 코드
public static void main(String[] args) throws IOException, InterruptedException{
   Process pc = Runtime.getRuntime().exec("javac");
   InputStream input = pc.getInputStream();
   IOUtils.copy(input, System.out);
   int exitCode = pc.waitFor();
   System.out.println(exitCode);
}