Reputation: 69
How can I restart my Java Console Application.
I want to create a method that when it's being called it restart or relaunch the console application. Can you guys give me some ideas how can I do it?
Upvotes: 2
Views: 5033
Reputation: 51
Theoretically, you should be able to called Runtime.exec() and pass in the command to run your Java Console App.
For precaution, prior to calling Runtime.exec(), you should save all the data or reach the state where your application is ready to exit. As Runtime.exec() will execute another instance of console app, and the new instance could have loaded all the data.
After successfully called Runtime.exec(), the existing app can peacefully die off.
Let me know if this can be done, as my concern is whether the new instance will be killed off when the existing app exited.
Upvotes: 0
Reputation: 17422
I can't think of a way to do it using just Java, you will need some help from scripting. You could restart by finishing the JVM execution with System.exit() and using a special value for the caller to know if it needs to be restarted rather than finished. So in your Java code you would have something like this:
public class Test {
public static final int RESTART_CODE = 100;
public static void main(String ... args) throws IOException {
// DO something...
restart();
}
static void restart() {
System.exit(RESTART_CODE);
}
}
And then a script invoking the JVM (in this case a Linux bash script, you could do something similar with a *.bat file if you're using Windows). Tee script:
#!/bin/bash
java Test "$@"
[ $? == 100 ] && ./test.sh "$@"
An then you can call your program with
java.sh _argument1_ _argument2_ ...
Upvotes: 2
Reputation: 10959
Have you tried calling main(args)
passing in String[] args
If you really want a restart()
method you could do something like
private void restart(String[] strArr)
{
main(strArr);
}
Crude mini example
import java.io.*;
public class Test{
public static void main(String[] args)
{
try{
System.out.println("Type 'R' to restart");
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String input = br.readLine();
if(input.equals("R"))
restart(args);
else
System.out.println("You did not restart");
}
catch(Exception e)
{e.printStackTrace();}
}
private static void restart(String[] strArr)
{
System.out.println("You restarted");
main(strArr);
}
}
Upvotes: 3