Reputation: 113
Probably a misleading title, but thanks to people on my other question, I got my program somewhat working, though now not sure what to do.
Here is my method to run command prompt commands and return the output
public static String cmdExec(String cmdLine) {
String line;
String output = "";
try {
Process p = Runtime.getRuntime().exec(cmdLine);
BufferedReader input = new BufferedReader(new InputStreamReader(p.getInputStream()));
while ((line = input.readLine()) != null) {
output += (line + '\n');
}
input.close();
}
catch (Exception ex) {
ex.printStackTrace();
}
return output;
}
It works how I want it to work, though now when I run this method, it is going to wait until everything is done, and then return the output, which is not what I want.
I made a ping flooding method that uses the cmdExec method. Here is how I call cmdExec()
String[] input = ipTextField.getText().split(":");
if(input.length == 2) {
System.out.println(cmdExec("cmd /c ping " + input[0] + " -t -n " + Integer.parseInt(input[1])));
So now for instance, if I type "127.0.0.1:3" in my program, it's going to send 3 packets to localhost. Now the problem here is, instead of printing out the lines I get as output from command prompt 1 by 1, it's going to wait until all the 3 packets are sent, and then print the output full output.
If I type "ping 127.0.0.1 -t -n 3" in command prompt, it's going to print the reply 1 by 1, not all just at once, so how would I go about doing the same in my program?
Upvotes: 3
Views: 3931
Reputation:
You can print out continuously with:
while ((line = input.readLine()) != null) {
System.out.println(line);
output += (line + '\n');
}
(The following is still useful for future viewers, but is not an applicable answer to the question.)
Simply insert a process.waitFor()
before reading from the output stream. This command waits until a process dies before continuing. You then don't have to read line by line, either. You can simply dump the buffer all at once.
Either this, or you can find a string which only occurs on the last line (e.g. Minimum
in Windows) and change the while condition to:
while((line == input.readline()).indexOf("Minimum") == -1)
Upvotes: 0
Reputation: 111
Instead of
while ((line = input.readLine()) != null) {
output += (line + '\n');
}
To output the results to the command line immediately just print within the while loop
while ((line = input.readLine()) != null) {
System.out.println(line);
output += (line + '\n');
}
Upvotes: 2