问题
I was trying to use a restartApplication method that I found on stack overflow, but for some reason it only will restart my application once. For example, in this simple JOptionPane program below, if the user enters the letter "a", it will restart the program. Once the program restarts, if the user types in "a" again, it just terminates the execution. How can I enable it to restart itself continuously?
I added in some println() statements to see if I could get any more info, and it just confirmed that the program is ending right after I type in the letter "a" on the second time around.
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import javax.swing.JOptionPane;
public class JOptionTest{
public static void restartApplication()
{
final String javaBin = System.getProperty("java.home") + File.separator + "bin" + File.separator + "java";
final File currentJar = new File("C:\\Documents and Settings\\My Documents\\hello3.jar");//UpdateReportElements.class.getProtectionDomain().getCodeSource().getLocation().toURI());
/* is it a jar file? */
if(!currentJar.getName().endsWith(".jar"))
return;
/* Build command: java -jar application.jar */
final ArrayList<String> command = new ArrayList<String>();
command.add(javaBin);
command.add("-jar");
command.add(currentJar.getPath());
final ProcessBuilder builder = new ProcessBuilder(command);
try {
builder.start();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.exit(0);
}
public static void main(String[] args){
String str = JOptionPane.showInputDialog(null, "Enter some text",1);
System.out.println(str);
//String a= "a";
if (str.equals("a")){
System.out.println(str+ "right about to restart");
restartApplication();
}
}
}
回答1:
See this line?
System.exit(0);
you are calling restartApplication a Single time and when it ends you exit the java process.
If you want to restart continuously, then remove this line and probably iterate forever:
public static void restartApplication()
{
while(true){
final String javaBin = System.getProperty("java.home") + File.separator + "bin" + File.separator + "java";
final File currentJar = new File("C:\\Documents and Settings\\XBBKKYL\\My Documents\\hello3.jar");//UpdateReportElements.class.getProtectionDomain().getCodeSource().get Location().toURI());
/* is it a jar file? */
if(!currentJar.getName().endsWith(".jar"))
return;
/* Build command: java -jar application.jar */
final ArrayList<String> command = new ArrayList<String>();
command.add(javaBin);
command.add("-jar");
command.add(currentJar.getPath());
final ProcessBuilder builder = new ProcessBuilder(command);
try {
builder.start();
} catch (IOException e) {
e.printStackTrace();
}
}
}
I have not tested this, it's just an idea
来源:https://stackoverflow.com/questions/11906769/java-restartapplication-method-only-restarts-once