Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
439 views
in Technique[技术] by (71.8m points)

process - External program from our Java program

How can I write a program in Java that will execute another program? Also, the input of that program should be given from our program and the output of that program should be written into a file.

This is my small set of code to get its output:

Process p = Runtime.getRuntime().exec("C:\j2sdk1.4.0in\helloworld.java");
BufferedReader input =
        new BufferedReader(new InputStreamReader(p.getInputStream()));
while ((line = input.readLine()) != null) 
  System.out.println(line);

input.close();

This was my set of code but this throws an IOException.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

The API that Java offers for this is the ProcessBuilder. It is relatively straightforward to set working directory and pass parameters.

What is a little tricky is passing STDIN and reading STDERR and STDOUT, at least for non-trivial sizes thereof, because you need to start seperate threads to make sure the respective buffers get cleared. Otherwise the application that you called might block until it can write more output, and if you also wait for that process to finish (without making sure that STDOUT gets read), you will deadlock.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...