Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
473 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 Answer

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...