I am trying to read real-time the data from a process using a BufferedReader and redirect it to a TextArea. However, I have noticed that when the process is running the .bat, it tends to freeze and cause a lag to the JavaFX TextArea. The ".bat" fiel that runs prints out a .....
one one line to indicate progress, and I believe this is where it is failing at. I had an idea to have the program wait a certain amount of time, then it executes, but because its all on one line it also fails. Please help
Code:
while(iterator.hasNext()) {
Map.Entry mentry = (Map.Entry)iterator.next();
String taskPath = " /k d: && cd DATA\\Virtualization\\Users && ESXRun.bat";
ProcessBuilder pb = new ProcessBuilder("cmd",taskPath);
Process process = pb.start();
BufferedReader stdInput = new BufferedReader(new InputStreamReader(process.getInputStream()));
String s = "";
// read the output from the command
while ((s = stdInput.readLine()) != null) {
//TextArea
cliLog.appendText(s);
cliLog.appendText("\n");
}
process.waitFor();
process.destroy();
}
This is just the concept to demonstrate the issue. You have to customize it and handle exceptions.
public class TextAreaBash extends Application implements Runnable {
private final TextArea textArea = new TextArea();
public static void main(final String[] args) {
Application.launch(args);
}
@Override
public void start(final Stage primaryStage) throws Exception {
primaryStage.setScene(new Scene(new VBox(textArea), 300, 200));
primaryStage.show();
ping();
}
public void ping() {
new Thread(this).start();
}
@Override
public void run() {
try {
final ProcessBuilder processBuilder = new ProcessBuilder("cmd", "/C", "ping -a www.google.com -n 10");
final Process process = processBuilder.start();
final InputStreamReader inputStreamReader = new InputStreamReader(process.getInputStream());
while (appendText(inputStreamReader)) {
;
}
process.waitFor();
process.destroy();
} catch (final Exception ex) {
ex.printStackTrace();
}
}
private boolean appendText(final InputStreamReader inputStreamReader) {
try {
final char[] buf = new char[256];
final int read = inputStreamReader.read(buf);
if (read < 1) {
return false;
}
Platform.runLater(() -> {
textArea.appendText(new String(buf));
});
return true;
} catch (final IOException e) {
e.printStackTrace();
}
return false;
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.