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
344 views
in Technique[技术] by (71.8m points)

java - How to capture the data returned from an EXE excuted from a batch?

I've a batch file that needs to be invoked from a java program. The batch file in-turn invokes an EXE. The EXE program will return data which I want to handle. If the EXE prints data to console am able to capture it as follows. But when the EXE is returning data after its completion, am not able to capture it.

ProcessBuilder pb = new ProcessBuilder("foo.bat");
Process p = pb.start();
int exitValue = p.waitFor();
BufferedReader reader;

// System.out.println("Exit Value" + exitValue);
if (exitValue == 0) {
    reader = new BufferedReader(new InputStreamReader(p
            .getInputStream()));
} else {
    reader = new BufferedReader(new InputStreamReader(p
            .getErrorStream()));
}

StringBuffer sb = new StringBuffer();
String temp = reader.readLine();
while (temp != null) {
    sb.append(temp);
    temp = reader.readLine();
}

reader.close();
System.out.println(sb.toString());

How do i need to capture the data returned by the EXE executed from a batch file?

The EXE is basically a C program. When I invoke the C program, the main method returns me the data, which I want to handle it.

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

Do you have control over the script? I'd try storing the return value (that's what you want?) from the executable to an environment variable. You may have to export it. Here's a tutorial on how to handle environment variables with Java.

Thanks to jitters comment - no, it doesn't work. We can't change values of the environment variable in a 'global' way (now I know..)

But, the idea works with a little adaptation: I'd still try to store the return value in a global accessible resource: Simply send the return value to a file (exec myapp > result.txt) and read the value from that file in your java application.


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

1.4m articles

1.4m replys

5 comments

57.0k users

...