I have the simple batch file code, which is working:
set path=%path%;C:\Program Files (x86)\Java\jdk1.7.0_05\bin
javac C:\Users\Ian\Desktop\batchFileTest\GUI.java
java -splash:images/splashImage.jpg GUI
However, it only takes like 1 second for my GUI class-file to load, and then the splash-screen immediately closes and launches the program.
I want to make the splash-screen wait for 5 seconds. My idea was to first execute the splash-screen without the class-file, to use TIMEOUT, and then to execute the class-file like this:
set path=%path%;C:\Program Files (x86)\Java\jdk1.7.0_05\bin
javac C:\Users\Ian\Desktop\batchFileTest\GUI.java
java -splash:images/splashImage.jpg
TIMEOUT 5
java GUI
This isn't working correctly either. The splash-screen is then displayed for some milliseconds and is closed immediately. The command-line then waits for 5 seconds, and then the program is launched.
Any ideas on how to correctly do this from a batch file?
Thanks to Greg here, I have a solution where I am delaying the splash-screen from the main method using Thread.sleep.
Here is the batch file:
set path=%path%;C:\Program Files (x86)\Java\jdk1.7.0_05\bin
javac C:\Users\Ian\Desktop\batchFileTest\GUI.java
java -splash:images/splashImage.jpg GUI
...and here is the class with the main method:
class GUI {
public static void main(String[] args) {
try {
Thread.sleep(5000); // the parameter is in milliseconds
catch(InterruptedException e) {
System.out.println(e.getMessage());
}
/*
* do whatever stuff here
*/
}
} // end of GUI
Related
Starting a java command line application is easy, you only have to write the following line in a command prompt (in the directory where the app is located).
java myApp.java
However, to stop the application in the right way, so that you ensure that all unmanaged resources are cleaned (and anything that must be done before stop, will be done) requires custom code.
The app will run in a debian system with no GUI as a daemon (it will run in background).
Here below I write the skeleton of the code.
public class MainClass {
public static void main(String[] args) throws Exception {
boolean stop = false;
while(!stop){
doSomething();
}
stop();
}
private static void doSomething(){
//Main code of app here
}
private static void stop(){
beforeStop();
System.exit(0);
}
private static void beforeStop(){
clean();
//Code to do anything you have to do before stop
}
private static void clean(){
//Code to clean unmanaged resources
}
}
As you can see, the app will run 24/24 and won't stop until you don't stop it.
Killing the process (as some people suggest) is not a good solution, because (for example) some unmanaged resources might not be cleaned properly.
I need a code which makes possible to alter the boolean variable "stop" from OUTSIDE.
The best solution is the one which makes possible to stop the app with a command similar to the start command, see pseudo code below (executed in a command prompt, in the directory where myApp.java is located).
myApp.java stop=true
But if it's not possible, the second option would be to have an other java command line app, which stops myApp.java, so that I could stop myApp.java with the following code
java stopMyApp.java
Is someone able to suggest a useful code example?
You can use a text file with one word. Your program reads it every x seconds and depending on that word it will autostop.
You can change the file text content by hand or with another program you can run whenever you want.
Even better you can use WatchService API (Java 7) or VFS API from Apache Commons to be notified when the file changes.
If you use a DB you can use it instead of a plain file.
[NB. This is related to How do I launch a completely independent process from a Java program? but different]
I want to be able to spawn external processes (shell scripts) from a "manager" Java process that should keep running when the JVM is killed - but it seems that when I kill the parent Java program the child is killed too (note, the behaviour is different if the JVM exits naturally). The simplest test program I have is:
public class Runit {
public static void main(String args[]) throws IOException, InterruptedException {
Runtime.getRuntime().exec(args[0]);
// doesn't work this way either
// ProcessBuilder pb = new ProcessBuilder(args[0]);
// pb.start();
while (true) {
System.out.println("Kill me");
Thread.sleep(2000);
}
}
}
and external script:
#!/bin/sh
while [ 1 ] ; do
ls
sleep 1
done
run as
java -classpath jar-with-dependencies.jar temp.exec.Runit runit.sh
If the manager simply exits (i.e. take out the "while" loop in the Java program) then the spawned process keeps running, but when I Ctrl+c the Java program the external program is killed too which is not what I want.
I'm using OpenJDK 1.6 on Ubuntu.
Edit1: Changing the exec to
Runtime.getRuntime().exec("/usr/bin/nohup " + args[0]);
doesn't help.
Edit2: Adding a shutdown hook as described in How to gracefully handle the SIGKILL signal in Java doesn't stop the Ctrl+c being propagated to the child.
Vladimir gave the hint we needed! (Sorry, beat Lukasz to it)
Add another script spawn_protect.sh
#!/bin/sh
LOG=$1
shift
nohup $* > $LOG 2>&1 &
And change the manager to:
public class Runit {
public static void main(String args[]) throws IOException, InterruptedException {
Runtime.getRuntime().exec(args);
while (true) {
System.out.println("Kill me");
Thread.sleep(5000);
}
}
}
Then run as:
java -classpath jar-with-dependencies.jar temp.exec.Runit spawn_protect.sh /tmp/runit.log runit.sh
Now runit.sh is really detached from the JVM process!
In Linux, if you start another process, it is your child and you are his parent. If parent gets killed, all children get killed, and their children too (what a terrible atrocity).
What you need, is to start a process that won't be killed when you exit your program. So, you need to give birth to not your own child. The methods to do that are described for example here: Linux: Prevent a background process from being stopped after closing SSH client for example use screen utility.
You've got to make it a daemon. Don't be afraid it's not a horror movie. Simply you'll need to detach your processes from controlling terminal session. I've always do it in a oposite way: shell script that launches Java.
Here is an explanation:
http://en.wikipedia.org/wiki/Daemon_(computing)
You can also you "jvm shutdown hooks", but they will not work in some situations.
I have written a java program and I am running it through command line like "java MyProgram"
Now I want to have a GUI that have a start, pause and stop button. How to start that java program by clicking on start button. How to pause it and how to stop it?
I assume your program is something like:
public class MyProgram {
public void doSomething() {
// ... does something ...
}
public static void main(String[] args) {
new MyProgram().doSomething();
}
}
I recommend reading the Swing Tutorial, but a simple GUI to launch your program could be something like:
public class MyProgramLauncher {
public static void main(String[] args) {
final MyProgram myProgram = new MyProgram();
JFrame frame = new JFrame("My Program");
JComponent cp = frame.getContentPane();
cp.add(new JButton(new AbstractAction("Start") {
public void actionPerformed(ActionEvent e) {
myProgram.doSomething();
}
}));
frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
frame.pack();
frame.setVisible(true);
}
}
If your class has a pause() function, you could add a similar JButton to call that function, but you'd have to write/implement the function.
You would, however, have to launch this with java MyProgramLauncher, which isn't very exciting. Still, that will get you a basic GUI in which you can experiment with starting, pausing, etc.
To turn your program into something you can double-click on, you'll need to create a JAR file. This is basically a special ZIP file that includes all the classes in your application, plus a manifest.xml file that describes those classes and (for launchable JAR files) identifies the "main class" whose main() method should be called when the JAR file is launched.
To turn that JAR file into a more or less self-contained deployable application is a bigger pain and there are a whole lot of options. The Deployment Tutorial might be a place to start.
Basically you need a native launcher, but I cannot figure out what do you mean exactly by "pause"... Sending the process to sleep?
I think that should be very easy to implement with a shellscript using the xdialog command in a Unix like system.
You'll need to implement a state machine:
State: "Stopped"
Start: execute java YourProgram and store the PID in a variable. Change state to "Started"
Pause: do nothing/disabled
Stop: do nothing/disabled
State: "Started"
Start: do nothing/disabled
Pause: send the STOP signal (like ctr+z) to the process. Change state to "Paused"
Stop: send the INT signal (like ctr+c) to the process. Change state to "Stopped"
State "Paused"
Start: do nothing/disabled
Pause: send the CONT signal (like doing fg) to the process. Change start to "Started"
Stop: send the INT signal (like ctr+c) to the process. Change state to "Stopped"
With this, you can loop in the script and react to the buttons. Look the reference for kill and dialog or xdialog for more details on the implementation.
First you need to write your "Forms"...
This will be a helpful resource to a beginner.
Basics
This question already has answers here:
Closed 13 years ago.
Possible Duplicate:
Is there a way to the hide win32 launch console from a Java program (if possible without JNI)
When I run my java swing application in a batch file on windows, the console/command window remains open whilst my java application is running. This creates an extra window on my taskbar which I would prefer not to have. But when I close the command window it stops my java application. Is there a way, perhaps via the batch file or command line parameters or code changes to my application, to have java.exe exit after bringing up my swing app and the console window close whilst my application still runs?
Main method is as follows:
public static void main(String args[]) {
ApplContext applContext = new ApplContext();
Throwable error = null;
try {
applContext.setUserConfigDir(args.length>0 ? args[0] : null);
applContext.loadData();
ApplTools.initLookAndFeel(Parameters.P_NIMBUS_LAF.of(applContext.getParameters()));
} catch (Throwable e) {
error = e;
}
// JWorkSheet is a JFrame.
new JWorkSheet(applContext, error).setVisible();
}
Run your application with javaw.exe rather than java. If you're running from a bat file, use this in combination with the start command:
> start javaw.exe -jar myapp.jar
When run in this mode, it's a good idea to set up proper logging or at least redirect your output streams if you rely on the console for any debugging. For example, with no console, you'll never see those friendly stack traces printed for unhandled exceptions.
Note: java.exe is a Windows console application. As such, no matter how it is started, or what threads are running in it, a console will be allocated for it. This is the reason that javaw.exe exists.
Ideally what you will eventually do somewhere in your code is call SwingUtilities.invokeLater(Runnable r). That will throw your GUI code into the correct thread, and you should be able to close the command line after the main thread exits.
This is a basic example of what I am talking about:
public static void main(String[] args){
SwingUtilities.invokeLater(new Runnable(){
public void run(){
JFrame yourWindow = new YourFrame();
yourWindow.createAndShow();
}
}
}
I am working on a program written in Java which, for some actions, launches external programs using user-configured command lines. Currently it uses Runtime.exec() and does not retain the Process reference (the launched programs are either a text editor or archive utility, so no need for the system in/out/err streams).
There is a minor problem with this though, in that when the Java program exits, it doesn't really quit until all the launched programs are exited.
I would greatly prefer it if the launched programs were completely independent of the JVM which launched them.
The target operating system is multiple, with Windows, Linux and Mac being the minimum, but any GUI system with a JVM is really what is desired (hence the user configurability of the actual command lines).
Does anyone know how to make the launched program execute completely independently of the JVM?
Edit in response to a comment
The launch code is as follows. The code may launch an editor positioned at a specific line and column, or it may launch an archive viewer. Quoted values in the configured command line are treated as ECMA-262 encoded, and are decoded and the quotes stripped to form the desired exec parameter.
The launch occurs on the EDT.
static Throwable launch(String cmd, File fil, int lin, int col) throws Throwable {
String frs[][]={
{ "$FILE$" ,fil.getAbsolutePath().replace('\\','/') },
{ "$LINE$" ,(lin>0 ? Integer.toString(lin) : "") },
{ "$COLUMN$",(col>0 ? Integer.toString(col) : "") },
};
String[] arr; // array of parsed tokens (exec(cmd) does not handle quoted values)
cmd=TextUtil.replace(cmd,frs,true,"$$","$");
arr=(String[])ArrayUtil.removeNulls(TextUtil.stringComponents(cmd,' ',-1,true,true,true));
for(int xa=0; xa<arr.length; xa++) {
if(TextUtil.isQuoted(arr[xa],true)) {
arr[xa]=TextDecode.ecma262(TextUtil.stripQuotes(arr[xa]));
}
}
log.println("Launching: "+cmd);
Runtime.getRuntime().exec(arr);
return null;
}
This appears to be happening only when the program is launched from my IDE. I am closing this question since the problem exists only in my development environment; it is not a problem in production. From the test program in one of the answers, and further testing I have conducted I am satisfied that it is not a problem that will be seen by any user of the program on any platform.
There is a parent child relation between your processes and you have to break that.
For Windows you can try:
Runtime.getRuntime().exec("cmd /c start editor.exe");
For Linux the process seem to run detached anyway, no nohup necessary.
I tried it with gvim, midori and acroread.
import java.io.IOException;
public class Exec {
public static void main(String[] args) {
try {
Runtime.getRuntime().exec("/usr/bin/acroread");
} catch (IOException e) {
e.printStackTrace();
}
System.out.println("Finished");
}
}
I think it is not possible to to it with Runtime.exec in a platform independent way.
for POSIX-Compatible system:
Runtime.getRuntime().exec(new String[]{"/bin/sh", "-c", "your command"}).waitFor();
I have some observations that may help other people facing similar issue.
When you use Runtime.getRuntime().exec() and then you ignore the java.lang.Process handle you get back (like in the code from original poster), there is a chance that the launched process may hang.
I have faced this issue in Windows environment and traced the problem to the stdout and stderr streams. If the launched application is writing to these streams, and the buffer for these stream fills up then the launched application may appear to hang when it tries to write to the streams. The solutions are:
Capture the Process handle and empty out the streams continually - but if you want to terminate the java application right after launching the process then this is not a feasible solution
Execute the process call as cmd /c <<process>> (this is only for Windows environment).
Suffix the process command and redirect the stdout and stderr streams to nul using 'command > nul 2>&1'
It may help if you post a test section of minimal code needed to reproduce the problem. I tested the following code on Windows and a Linux system.
public class Main {
/**
* #param args the command line arguments
*/
public static void main(String[] args) throws Exception {
Runtime.getRuntime().exec(args[0]);
}
}
And tested with the following on Linux:
java -jar JustForTesting.jar /home/monceaux/Desktop/__TMP/test.sh
where test.sh looks like:
#!/bin/bash
ping -i 20 localhost
as well as this on Linux:
java -jar JustForTesting.jar gedit
And tested this on Windows:
java -jar JustForTesting.jar notepad.exe
All of these launched their intended programs, but the Java application had no problems exiting. I have the following versions of Sun's JVM as reported by java -version :
Windows: 1.6.0_13-b03
Linux: 1.6.0_10-b33
I have not had a chance to test on my Mac yet. Perhaps there is some interaction occuring with other code in your project that may not be clear. You may want to try this test app and see what the results are.
You want to launch the program in the background, and separate it from the parent. I'd consider nohup(1).
I suspect this would require a actual process fork. Basically, the C equivalent of what you want is:
pid_t id = fork();
if(id == 0)
system(command_line);
The problem is you can't do a fork() in pure Java. What I would do is:
Thread t = new Thread(new Runnable()
{
public void run()
{
try
{
Runtime.getRuntime().exec(command);
}
catch(IOException e)
{
// Handle error.
e.printStackTrace();
}
}
});
t.start();
That way the JVM still won't exit, but no GUI and only a limited memory footprint will remain.
I tried everything mentioned here but without success. Main parent Java process can't quit until the quit of subthread even with cmd /c start and redirecting streams tu nul.
Only one reliable solution for me is this:
try {
Runtime.getRuntime().exec("psexec -i cmd /c start cmd.cmd");
}
catch (Exception e) {
// handle it
}
I know that this is not clear, but this small utility from SysInternals is very helpful and proven. Here is the link.
One way I can think of is to use Runtime.addShutdownHook to register a thread that kills off all the processes (you'd need to retain the process objects somewhere of course).
The shutdown hook is only called when the JVM exits so it should work fine.
A little bit of a hack but effective.