Reputation: 139
I have some code set up that is supposedly running the batch file. I'm not sure though because it's not showing anything in the console, but when I click the JButton PING, the button holds in the click for a couple seconds so it's definitely processing something. What I need help with is outputting the batch file to a JTextArea in my GUI. I'm not really sure how to direct my code to my JTextArea called "textarea". Can someone show me how you would add textarea into this code to get the output? Thanks!
JButton btnPingComputer = new JButton("PING");
btnPingComputer.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
try {
// create a new process
// System.out.println("Creating Process...");
Process p = Runtime.getRuntime().exec("c:\\ping.bat");
// get the input stream of the process and print it
InputStream in = p.getInputStream();
for (int i = 0; i < in.available(); i++) {
System.out.println("" + in.read());
}
for (int i = 0; i < in.available(); i++) {
textArea.append(in.read()+"\n");
}
// wait for 10 seconds and then destroy the process
p.destroy();
} catch (Exception ex) {
ex.printStackTrace();
}
}
});
Upvotes: 0
Views: 280
Reputation: 36
You could try this code, which will execute the batch file specified and read back anything the batch file echoes back. From there you should be able to take the input and append it to the JTextArea. As long as your bat echoes text back the batOutput should catch it. Watch out for formatting errors due to non-standard characters, however.
public static void main(String[] args) {
String batFile = "C:/test.bat";
try {
ProcessBuilder procBuild = new ProcessBuilder(batFile);
Process proc = procBuild.start();
InputStream streamIn = proc.getInputStream();
BufferedReader br = new BufferedReader(new InputStreamReader(streamIn));
String batOutput = null;
while ((batOutput = br.readLine()) != null) {
System.out.println(batOutput);
}
} catch (Exception e) {
e.printStackTrace();
}
}
Upvotes: 0
Reputation: 5395
Try this:
for (int i = 0; i < in.available(); i++) {
textarea.append(in.read()+"\n");
}
EDIT:
I think there could be also a problem with in.available()
. You can try to change this completly:
String line;
Process p = Runtime.getRuntime().exec("c:\\ping.bat");
BufferedReader in = new BufferedReader(new InputStreamReader(p.getInputStream()));
while ((line = in.readLine()) != null) {
System.out.println(line);
textarea.append(line);
}
in.close();
Upvotes: 1