I\'m making a program that runs a few cmd commands (USMT and file transfer)
It\'s working fine, but I only get the last line from the cmd in my text box and only af
At the moment, you are reading the command output using readLine(), and then you are directly putting it into setText().
To make the code update it in real time, we are defining a new Thread and use that thread to read over the OutputStream over the socket:
public void load() throws IOException {
Thread t = new Thread(() -> {
try {
ProcessBuilder builder = new ProcessBuilder(
"cmd.exe", "/c", "cd \"C:\\usmt\" && loadstate.bat");
builder.redirectErrorStream(true);
Process p = builder.start();
BufferedReader r = new BufferedReader(new InputStreamReader(p.getInputStream()));
String line;
while (true) {
line = r.readLine();
if (line == null) {
break;
}
String l = line;
SwingUtilities.invokeLater(new Runnable() {
public void run() {
cOut.setText(l);
}
});
System.out.println(line);
}
} catch (IOException ex) {
ex.printStackTrace(); //Add a better error handling in your app
}
});
t.start();
}
Above, we define a new thread that is used to read the lines.
Sometimes, you need to put all the lines the command is printing on screen, this is easy to do using a StringBuilder:
String line;
StringBuilder total = new StringBuilder();
while (true) {
line = r.readLine();
if (line == null) {
break;
}
total.append(line).append('\n');
cOut.setText(total.toString());
System.out.println(line);
}
The above uses a StringBuilder to temporary store the finished result, before writing it to the screen.