Showing posts with label Java. Show all posts
Showing posts with label Java. Show all posts

Monday, January 14, 2013

Get the path of a running jar file

When code is running inside a jar file, say foo.jar, and we need to know, in the code, in which folder the running foo.jar is use this command in the Java code.


 return new File(MyClass.class.getProtectionDomain().getCodeSource().getLocation().getPath());
Another of achieving the same is using the following code:
String path = Test.class.getProtectionDomain().getCodeSource().getLocation().getPath();
String decodedPath = URLDecoder.decode(path, "UTF-8");
Reference:
http://stackoverflow.com/questions/320542/how-to-get-the-path-of-a-running-jar-file

Tuesday, October 2, 2012

Add external jar files in classpath when running Java programs from command prompt or shell

If you simply want to compile or run Java applications from command line, you can just add the jars to the classpath:
javac -classpath c:\path1\ext1.jar;d:\path2\ext2.jar de\example\MyClass.java

When running a java application, you have to add the classes folder as well
java -classpath bin;c:\path1\ext1.jar;d:\path2\ext2.jar de.example.MyClass

When running from command prompt on windows, you can also replace "bin" with a "."

Note that under *nix OS not a semicolon(;), but a colon(:) is used to separate classpath parts.

Reference:
1. http://www.coderanch.com/t/423052/java/java/solved-add-external-jar-windows

Run Java console application by double click

Assume you have written a console java application in Eclipse and want to distribute it to users as an executable. You export the class files as an executable JAR file from eclipse, however to run the JAR file you need to use Windows Command Prompt and type in the command
java -jar Filename.jar arguments

To make it more easily runnable - by a double click - we need to create a .bat file with the following contents  and present in the same folder as the JAR file.

@echo off
 set jarpath="JavaApp.jar"
 java -jar %jarpath% %CD%Config.txt
 PAUSE

Here, %CD% is a pseudo-variable which holds the working directory. It’s useful when you want to load a config file located in the same folder as your .bat file. You can also replace it with any arguments for the JAR file. PAUSE displays a localized version of “Press any key to continue…” message.

References:
http://blog.mwrobel.eu/how-to-properly-run-java-consol-application-with-a-doubleclick-windows/