Reputation: 41
I'm on Windows 10, using ProcessBuilder to run a .exe from my Java program and using BufferedReader to get the number it outputs when it's provided the path that my Java program provides. It's working, but it's freezing the program for an unbearable while when it tries to get the output.
It worked smoothly when I tested it on Ubuntu 20, but I can't make it go fast on Windows. Also, if I run the .exe file from cmd, it goes fast as it should.
Here's my Main class code:
package teste;
import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
boolean isWindows = System.getProperty("os.name").toLowerCase().startsWith("windows");
Process process;
String command = "src\\teste\\flir_image_extractor.exe -avg -i C:\\Users\\Daniel\\Desktop\\example.jpg";
try {
ProcessBuilder builder = new ProcessBuilder();
if (isWindows) {
builder.command("cmd.exe", "/c", command);
} else {
builder.command("sh", "-c", command);
}
System.out.println("this");
builder.directory(new File(System.getProperty("user.dir")));
builder.redirectErrorStream(true);
process = builder.start();
BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
String line = "";
while ((line = reader.readLine()) != null) {
System.out.println(line); // Do something with the return
}
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
I tested it with prints, and it hangs just as it enters the while loop, so it looks like readLine()
is the issue. Does anyone know what could be slowing it down?
I'm running the code in Eclipse.
I thank you in advance.
Upvotes: 0
Views: 578
Reputation: 15196
A few things to try. It may be the Eclipse console - some versions have been slow if there is a lot of output. You could test this by running this Java app from Windows command line to see if issue goes away, or you could remove your reader.readLine() / System.out.println
loop and replace with transferTo:
try(var stdo = p.getInputStream()) {
stdo.transferTo(System.out);
}
Don't forget to wait for the process exit:
int rc = exec.waitFor();
If the Eclipse console is the issue, redirect output to a file before start and check the file afterwards:
pb.redirectOutput(new File("stdout.log"));
Ideally, don't use CMD.EXE / shell to run applications that may be run directly, try as:
String[]command = new String[] {"src\\teste\\flir_image_extractor.exe","-avg", "-i", "C:\\Users\\Daniel\\Desktop\\example.jpg"};
Upvotes: 1