I have comand line application in Java. Can I write code for double click on JAR file and app start run in comand prompt(automatic open).
Thanks for answers.
Did you try this:
Right Click > Properties > Change > C:\Program Files\Java\jre8\bin\javaw.exe
This has been resolved here How to run .jar file by double click on Windows 7 (64)
Assuming your problem is, that your jar runs silent in background and you don't see output:
Usually this is not possible using only 1 file and you would need to create a .BAT with the following next to your .JAR:
java -jar jourJar.jar
It's possible to use a wrapper, like Fast Snail suggested.
You still can do it with pure java code using 1 file with something like the following, but it's more a hack.
public static void main(String[] args){
if(args.length > 0 && args[0].equals("instance")){
//start your real application code here
}else{
Runtime.getRuntime().exec(new String[]{"cmd", "java", "-jar", "jourJar.jar", "instance"});
}
}
This will open the JAR and then it creates a new CMD process running the JAR again.
Related
I've created Java runtime image for a simple OpenJFX application. In order to run this app, jlink auto-generated two lauch scripts under %image_path%/bin directory. This how it looks like (the one for Windows):
#echo off
set JLINK_VM_OPTIONS=
set DIR=%~dp0
"%DIR%\java" %JLINK_VM_OPTIONS% -m app/com.package.Launcher %*
Obviously, when I run this batch file it opens new shell window, which is not what I want to. I've tried all common approaches: use javaw instead of java, run script via start command etc. Nothing works.
Is it possible to avoid shell window or somehow create native launcher?
Ok, I've figured out it's not posiible to eliminite shell window completely. In the best scenario it's just flickers for ~1sec. This is how it can be achieved:
#echo off
set JLINK_VM_OPTIONS=
set DIR=%~dp0
start "" "%DIR%\javaw" %JLINK_VM_OPTIONS% -m app/com.package.Launcher %* && exit 0
There is a feature request about native laucher implementation but it's not discussed actively.
Nonetheless I've solved the problem. There is "Batch to EXE Converter" tool. It can generate executable (basically the same batch file) which can run your app silently.
This looks to be possible using vbscript. If you put the following script into a .vbs file next to the launcher.bat file (or whatever the name of the batch file is):
CreateObject("Wscript.Shell").Run CreateObject("Scripting.FileSystemObject").GetParentFolderName(WScript.ScriptFullName) & "\launcher.bat " & WScript.Arguments(0) & " > " & CreateObject("Scripting.FileSystemObject").GetParentFolderName(WScript.ScriptFullName) & "\launch-log.log", 0, False
This runs the batch file in the same directory, and also redirects stdout to a log file.
What you´d like to achieve is very well possible. It is actually even quite easy and I use this every day. There already is an early access build of jpackage available here: http://jdk.java.net/jpackage/ Creating executables works already
nicely (I use it on Mac and Windows). Only creating installers is still a bit problematic.
It's very easy to run a bat file without showing the cmd window.
you just need to create VBS file to run bat file with the following cmd
Set WshShell = CreateObject("WScript.Shell")
WshShell.Run chr(34) & ".\bin\launcher.bat" & Chr(34), 0
Set WshShell = Nothing
Save cmd in the file out of the bin folder with any name like
Launcher.vbs.
I'll start of by saying Im on windows 7.
I have created a .jar file which executes fine from the command line using the - java -jar myJar.jar approach
But what I'm after is to be able to double click on the jar file and for it to open up the command prompt window and run in the command prompt as if i've just typed the java -jar myJar.jar line.
When I double click the jar file I do think it is running because a visual part of the java is appearing, but there is no command prompt window showing my console output.
After looking around I've come across people saying that javaw which is what the jar files are associated with don't have a console and that I need to associate jar files with java.exe instead of javaw.exe. I've tried this and it didn't seem to work.
Can anyone help? A step by step would be nice.
I had the same question and the bat file idea was genius and saved me a lot of time rewriting code. Thanks!(I would have upvoted,but apparently I don't have enough rep.)
Batch (or Bat) files are super easy to make.
Just put the java -jar YourFile.jar into notepad (if you're on windows), save as Title.bat, and put into the same folder as your jar.
presto! a program open-able by the general public.
This is IMHO not possible. You could open the console from the application itself, but that is OS-dependent. If you need the console open, you have to run the application from it as you already do.
If you want to display the command line you have to launch your jar with the command line.
java -jar MyJar.jar
I would do something like this:
(Tested in Widows XP with JRE 1.6, to support other OSs you should verify the path for each OS and select the appropriate console emulator (xterm, gnome-terminal... (check for existance and preference...)))
public static void main(String[] args) throws Exception {
if (args.length == 0) {
String path = Main.class.getProtectionDomain().getCodeSource().getLocation().getPath().substring(1);//Adds extra slash (??) didn't know why
String decodedPath = URLDecoder.decode(path, "UTF-8");
System.out.println(decodedPath);
Runtime.getRuntime().exec("cmd /c start java -jar \"" + decodedPath + "\" actual_run");
}
else {
System.out.println("Hello World");
JOptionPane.showMessageDialog(null, "Hello World");
System.in.read();
}
}
Alternatively I suggest creating a bat file with this content :
java -jar yourjar.jar
This will launch your jar as well as open the command prompt automatically, all from a simple double click on a bat file.
(The bat file needs to be in the same folder as your jar file, else you need to specify the path to the jar, not just the jar name)
This is the easiest solution for beginners:
Open any text editor
write this two lines:
java "yourmainclassname"
pause
save that file as "name".bat
Run it with double click from windows GUI
(of course this new created .bat file must be in the same folder as the .class)
..but there is no command prompt window showing my console output.
No there wouldn't be a console for an executable Jar. You'll need to put that output in the GUI.
Check your MANIFEST.MF
Extract your "executable" jar file into a folder
find MANIFEST.MF in META-INF folder
check presence of this field:
Main-Class: YourMainClassHere
If this field dissapeared then open your original MANIFEST.txt for this point:
Main-Class: YourMainClassHere must end with a new line or carriage return
Warning: The text file must end with a new line or carriage return. The last line will not be parsed properly if it does not end with a new line or carriage return.
import java.io.*;
public class Main {
public static void main(String[] args) throws IOException, StringIndexOutOfBoundsException
{
Runtime.getRuntime().exec("cmd /c start C:\\dig-files3\\query3.bat");
}
}
I'm trying to launch a batch file through a java program but I get a 'dig not recognized as an internal or external command ...' message in the cmd screen. However when I double click on the batch file in the window it runs fine. How can I fix this?
Here is the batch file's content:
SET /a VAR=0
:HOME
SET /a VAR=VAR+1
IF %VAR%==200000 goto :End
dig #10.3.1.166 6.4.0.3.5.5.5.9.9.9.com. naptr
goto :HOME
:END
This is probably happening because "dig" has not been added to your PATH variable. Try opening a new terminal window and typing "dig" and it will probably show the same error. You have to go to Control Panel -> System -> System Properties -> Advanced options tab -> Environment variables.
There you have to search for the PATH variable and add, at the end (and after adding ";" to the last command) the full path to "dig" executable (except for the executable itself e.g. c:\foo\bar). Then try again. This environment variable tells Windows to look on the list of paths contained in it, for the executable you are trying to run.
Another solution is to copy over your compiled java file to where the dig executable is located and run it from there.
You should create a file object for the working directory to prevent problems with whitespaces in the path and then use that object to start the batch script:
File workdir = new File("C:\\dig-files3");
Runtime.getRuntime().exec("query3.bat", null, workdir);
There's also a flaw in your batch script: You probably want to write SET /a VAR=%VAR%+1 so that %VAR% gets evaluated before incrementing it.
Your problem is that you do not have the batch file in the system PATH variable. Insert the path to your batch file into the system PATH and it should work fine
Ok, there may another way to fix this but this is how I did it. I am using Eclipse and I copied the dig application to the project directory C:\User\username\workspace\projectName
I need to run a bat file using a java code. I did that in the following way
Process process =Runtime.getRuntime().exec("cmd /c start D:\\Work\\BOSync\\TestFoxPro\\ATSFill.bat");
int exitVal = process.waitFor();
Problem is I can run the bat but the task of the bat not happened. I run the bat to load data from CSV file to oracle database using sqlldr. When I double click on the bat it works fine.
I think the problem is JVM doesn't has enough permission to run the bat. Is there a way to elevate the permission in java?
This sounds like a path issue to me. Try using absolute paths to the binary that you are using in your bat file and set other environment variables that your script need.
As for the cmd window popping up - try just calling the bat file directly and not use the cmd /c command.
Hey guys finally i Sort it out. The problem was in my bat file. It was like that previously. cd \C:\oracle\ora92\bin sqlldr GAMINI/gamini C:\AOTITS\CLSTMAS.ctl log=C:\AOTITS\CLSTMAS.log. Then I remove the path of oracle bin and add it to system path. Then it works fine. Thanks for your help
I'm making an editor-like program. If the user chooses File->Open in the main window I want to start a new copy of the editor process with the chosen filename as an argument. However, for that I need to know what command was used to start the first process:
java -jar myapp.jar blabalsomearguments // --- need this information
> Open File (fileUrl)
> exec("java -jar myapp.jar blabalsomearguments fileUrl");
I'm not looking for an in-process solution, I've already implemented that. I'd like to have the benefits that seperate processes bring.
Since you are launching Java -> Java, you can use the existing classpath to set the classpath on the command line. This type of thing works really nice in the dev environment too.
ProcessBuilder selfLauncher = new ProcessBuilder(
"java", "-cp", System.getProperty("java.class.path"),
"com.my.mainClass" );
selfLauncher.start();
Update:
For executable jar files, you will have a classpath which is simply the relative path to the jar file itself. If you want the command line arguments, you will have to save them from main, and re-apply them when launching.
You can see this by packing the following program into a jar. I'm not actually sure what happens if you have jars inside the executable jar file. They probably show up in the classpath.
public class TestJarPath {
public static void main(String args[]) throws Exception {
for (String s : args)
System.out.print("[" + s + "] ");
System.out.println();
String cp = System.getProperty("java.class.path");
for (String s : cp.split(";"))
System.out.println(s);
}
}
For java -jar ..\tst.jar X, you get output like:
[X]
..\tst.jar
If all else fails, try writing a batch/shell script to launch your app. In windows you can pass %CmdCmdLine% to Java to get the entire command line.
See http://www.robvanderwoude.com/parameters.php
As far as I know is there no portable way to get this info. I found a property in the gcj runtime but I doubt this will cover a large percentage of the users.
I think the accepted practice is "Try and Pray" :
Hope it is on the path, (the path IS available, so that can be checked)
if not, check if JAVA_HOME is defined, and use that to find java.
if not check in the most likely places on all OS's you have received bug reports for.
Well, it is messy... porbably best to check for JAVA_HOME and the path and ask the user to configure a JVL explicitely if that fails.