how can I execute a process in Java without the program freezing?
I've tried using SwingWorker, but I don't quite yet understand how it works.
Is there any other way I can accomplish this? I'm wanting to use something like this in my JDroidLib. For full source code, check out the GitHub: http://github.com/Team-M4gkBeatz/JDroidLib
Thanks in advance!
EDIT:
Thanks for your answers. But I have a class with several methods (well, it's more than one class, but you get my point); how can I use a SwingWorker to interact with those?
Here is one of the classes:
/**
*
* @author Simon
*/
public abstract class Command extends SwingWorker {
BufferedReader prReader = null;
ProcessBuilder process = null;
Process pr = null;
Date timeNow = new Date();
String osName = System.getProperty("os.name");
public void executeProcessNoReturn(String _process, String arg) throws IOException {
process = new ProcessBuilder(_process, arg);
pr = process.start();
}
public String executeProcessReturnLastLine(String _process, String arg) throws IOException {
process = new ProcessBuilder(_process, arg);
pr = process.start();
prReader = new BufferedReader(new InputStreamReader(pr.getInputStream()));
String line;
while ((line = prReader.readLine()) != null) {
// Wait for input to end.
}
return line;
}
public StringBuilder executeProcessReturnAllOutput(String _process, String arg) throws IOException {
process = new ProcessBuilder(_process, arg);
pr = process.start();
prReader = new BufferedReader(new InputStreamReader(pr.getInputStream()));
StringBuilder output = null;
String line;
while ((line = prReader.readLine()) != null) {
output.append(line);
}
return output;
}
public boolean isProcessRunning(String processName) throws IOException {
boolean value = false;
if (osName.equals("Linux") | osName.contains("Mac")) {
process = new ProcessBuilder("ps", "-e");
pr = process.start();
String line;
prReader = new BufferedReader(new InputStreamReader(pr.getInputStream()));
while ((line = prReader.readLine()) != null) {
if (line.contains(processName)) { value = true; break; }
}
} else {
String winDir = System.getenv("windir") + "/System32/tasklist.exe";
process = new ProcessBuilder(winDir);
pr = process.start();
String line;
prReader = new BufferedReader(new InputStreamReader(pr.getInputStream()));
while ((line = prReader.readLine()) != null) {
if (line.contains(processName)) { value = true; break; }
}
}
return value;
}
public String executeProcessReturnError(String processName, String arg) throws IOException {
process = new ProcessBuilder(processName, arg);
process.redirectError();
pr = process.start();
prReader = new BufferedReader(new InputStreamReader(pr.getErrorStream()));
String line;
String output = "";
while ((line = prReader.readLine()) != null) {
output += line + "
";
}
return output;
}
}
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…