How to find directory java program .jar file is in?
I have a Java program that needs to save some configuration and data files in the same directory as the .jar file that contains the program.
If the user launches the app from that directory, it's easy.
The problem is when they do something like "java -jar /dir1/dir2/program.jar".
When they do that, HOW can I find the directory the .jar file is in - from within the program?
CasaDelGato wrote:
I have a Java program that needs to save some configuration and data files in the same directory as the .jar file that contains the program.
If the user launches the app from that directory, it's easy.
The problem is when they do something like "java -jar /dir1/dir2/program.jar".
When they do that, HOW can I find the directory the .jar file is in - from within the program?There is an obscure way that basically consists of the following.
1. Get the class loader of the class (obviously one in the jar)
2. Find the 'resource' of that.
3. Resolve that to a path
4. Make it absolute if not already.
5. Extract the directory part.
2 and 3 are always the hard ones (conceptually and figuring out from the javadocs). There are examples somewhere on the forum.
Similar Messages
-
How to run tools from a java archive (jar file)
I used to run Multivalent from http://multivalent.sourceforge.net/ but am now getting error messages like this:
Exception in thread "main" java.lang.NoClassDefFoundError: tools/pdf/Impose
This happens even when I'm in the directory containing the jar file.
I've never installed it by myself though so am not sure that I've done it right. I put the jar file into ~/library/java but that was a guess after reading lots of web pages that don't quite say what to do. They assume that I've read some intro material that I haven't been able to find.
Any pointers on where I can find out how to do this right?
In case it's relevant, java -version returns:
java version "1.5.0_16"
Java(TM) 2 Runtime Environment, Standard Edition (build 1.5.0_16-b06-284)
Java HotSpot(TM) Client VM (build 1.5.0_16-133, mixed mode, sharing)
and echo $CLASSPATH returns a blank line.Not necessarily. The -cp parameter can include a complete file spec. You can create a Unix alias for the whole command line. For example:
alias compress='java -cp ~/JarFolder/Multivalent20060102.jar tool.pdf.Compress'
I use Multivalent tools a lot for maybe a week at a time, then don't touch them for a couple of months. During the downtime I'd just forget aliases like this.
On Macs, the default classpath includes the folder /Library/Java/Extensions. If you drop the jar file into this folder then you won't need to specify an explicit CLASSPATH variable nor the -cp option.
I thought so too, but it doesn't appear to be the case on my computer. Both /Library/java/extensions and ~/library/java are on DefaultClasspath but CLASSPATH is empty. And even when the directories are specified, the jar file in it is ignored unless I specify that explicitly as well. I do not remember needing to do that in the past. It used to just work when it was in a classpath directory.
I get the impression that something has changed in how Mac Java handles the classpath. In searching for answers I noticed that many people were attributing their difficulties to a classpath change in a recent update. It is not something that I see myself dealing with in the near future. But it would be helpful to know of a primer for newcomers to Java and the OS X directory conventions so they know where to put things and what paths to set for basics like this. -
How to detrmine what directory you (the JAR file) are in
Is there some sort of function that returns (ideally in a string, or array of strings) what directory you (the JAR file) are in? Something along the lines of:
String dir = Function();Then dir would be something like : "C:\Users and Settings\Me\Java Apps"
Thanks.It's not clear exactly what is wanted. Look at the information in the API for java.lang.System,getProperties(), which lists properties available - choos the one you want.
-
How to create and use library JAR files with command-line tools?
Development Tools -> General Questions:
I am trying to figure out how to put utility classes into JAR files and then compile and run applications against those JAR files using the command-line javac, jar, and java tools. I am using jdk1.7.0_17 on Debian GNU/Linux 6.0.7.
I have posted a simple example with one utility class, one console application class, and a Makefile:
http://holgerdanske.com/users/dpchrist/java/examples/jar-20130520-2134.tar.gz
Here is a console session:
2013-05-20 21:39:01 dpchrist@desktop ~/sandbox/java/jar
$ cat src/com/example/util/Hello.java
package com.example.util;
public class Hello {
public static void hello(String arg) {
System.out.println("hello, " + arg);
2013-05-20 21:39:12 dpchrist@desktop ~/sandbox/java/jar
$ cat src/com/example/hello/HelloConsole.java
package com.example.hello;
import static com.example.util.Hello.hello;
public class HelloConsole {
public static void main(String [] args) {
hello("world!");
2013-05-20 21:39:21 dpchrist@desktop ~/sandbox/java/jar
$ make
rm -f hello
find . -name '*.class' -delete
javac src/com/example/util/Hello.java
javac -cp src src/com/example/hello/HelloConsole.java
echo "java -cp src com.example.hello.HelloConsole" > hello
chmod +x hello
2013-05-20 21:39:28 dpchrist@desktop ~/sandbox/java/jar
$ ./hello
hello, world!I believe I am looking for:
1. Command-line invocation of "jar" to put the utility class bytecode file (Hello.class) into a JAR?
2. Command-line invocation of "javac" to compile the application (HelloConsole.java) against the JAR file?
3. Command-line invocation of "java" to run the application (HelloConsole.class) against the JAR file?
I already know how t compile the utility class file.
Any suggestions?
TIA,
DavidI finally figured it out:
1. All name spaces must match -- identifiers, packages, file system, JAR contents, etc..
2. Tools must be invoked from specific working directories with specific option arguments, all according to the project name space.
My key discovery was that if the code says
import com.example.util.Hello;then the JAR must contain
com/example/util/Hello.classand I must invoke the compiler and interpreter with an -classpath argument that is the full path to the JAR file
-classpath ext/com/example/util.jarThe code is here:
http://holgerdanske.com/users/dpchrist/java/examples/jar-20130525-1301.tar.gz
Here is a console session that demonstrates building and running the code two ways:
1. Compiling the utility class into bytecode, compiling the application class against the utility bytecode, and running the application bytecode against the utility bytecode.
2. Putting the (previously compiled) utility bytecode into a JAR and running the application bytecode against the JAR. (Note that recompiling the application against the JAR was unnecessary.)
(If you don't know Make, understand that the working directory is reset to the initial working directory prior to each and every command issued by Make):
2013-05-25 14:02:47 dpchrist@desktop ~/sandbox/java/jar
$ cat apps/com/example/hello/Console.java
package com.example.hello;
import com.example.util.Hello;
public class Console {
public static void main(String [] args) {
Hello.hello("world!");
2013-05-25 14:02:55 dpchrist@desktop ~/sandbox/java/jar
$ cat libs/com/example/util/Hello.java
package com.example.util;
public class Hello {
public static void hello(String arg) {
System.out.println("hello, " + arg);
2013-05-25 14:03:03 dpchrist@desktop ~/sandbox/java/jar
$ make
rm -rf bin ext obj
mkdir obj
cd libs; javac -d ../obj com/example/util/Hello.java
mkdir bin
cd apps; javac -d ../bin -cp ../obj com/example/hello/Console.java
cd bin; java -cp .:../obj com.example.hello.Console
hello, world!
mkdir -p ext/com/example
cd obj; jar cvf ../ext/com/example/util.jar com/example/util/Hello.class
added manifest
adding: com/example/util/Hello.class(in = 566) (out= 357)(deflated 36%)
cd bin; java -cp .:../ext/com/example/util.jar com.example.hello.Console
hello, world!
2013-05-25 14:03:11 dpchrist@desktop ~/sandbox/java/jar
$ tree -I CVS .
|-- Makefile
|-- apps
| `-- com
| `-- example
| `-- hello
| `-- Console.java
|-- bin
| `-- com
| `-- example
| `-- hello
| `-- Console.class
|-- ext
| `-- com
| `-- example
| `-- util.jar
|-- libs
| `-- com
| `-- example
| `-- util
| `-- Hello.java
`-- obj
`-- com
`-- example
`-- util
`-- Hello.class
19 directories, 6 filesHTH,
David -
How to call a java program in javafx class(Urgent) and even vice versa
Hi all,
Here I have two questions:
1)
Please let me know how to call a javafx in java program...
I tried with the following code but it is not working..
The below is the java program in which I made a call to the Fx program.
FxMainLauncher.java
import net.java.javafx.FXShell;
public class FxMainLauncher {
public static void main(String[] args) throws Exception {
FXShell.main(new String[] {"HelloWorld.fx"});
2) How to call a java program in javafx class
Here is my javafx program
import check.*;
import javafx.ui.*
var instance = new MyJava();
//visible:true
System.out.println("Number is: {instance}");
Here is my java program
public class MyJava {
public static void main(String args[])
System.out.println("JAVAFX TO JAVA");
Even this is not working please let me know ASAP
Thanks in advance,
V.SrilakshmiGOT IT !!!
I had to change the name of the method in .h file generated by javah command. On doing
javac -d ../../classes HelloWorld.java
go to the ../../classes directory (where you have the class file) and do
javah HelloWorld
I got a HelloWorld.h file in which I had
JNIEXPORT void JNICALL Java_HelloWorld_display(JNIEnv *, jobject);
I added the package name too:
JNIEXPORT void JNICALL Java_GUI_HelloWorld_display(JNIEnv *, jobject);
The HelloWorldImp.c file should have the same name (ie with package) and be in the same directory(ie ../../classes)
compile and build the shared library to get "libhello.so" file
gcc -c -fPIC -I/usr/lib/j2sdk1.3/include -I/usr/lib/j2sdk1.3/include/linux HelloWorldImp.c
gives .o file
gcc -shared -o libhello.so HelloWorldImp.o
gives .so file
then run java with the command in my first message. It works.
Thanks for the reply "thedracle". -
How to design a java program to java supported mobile phone
I need to know how to design a java program to java supported mobile phone and how to install it on mobile phone? also i need to know how to create a ".jar" file, because my mobile phone is require '.jar' files. if anyone know please let me know.
I need to know how to design a java program to java
supported mobile phone and how to install it on
mobile phone? also i need to know how to create a
".jar" file, because my mobile phone is require
'.jar' files. if anyone know please let me know.http://java.sun.com/j2me/index.jsp
http://java.sun.com/docs/books/tutorial/deployment/jar/index.html -
How to write the java program to retrieve the last 7 days dates
Hi,
I am having requirement that how to write the java program to retrieve the last 7 days dates. Please help me.
Regards,
AhamadIt needs any jar file.Of course!
I did using jscape.My program is running fine.But it
requires jar file.Which is licensed version.Maybe you should follow the link the the 'license' on the site I posted!
>
I have the doubt is apache provides jar file free
versionMaybe you should follow the link the the 'license' on the site I posted! -
How can I get a single jar file with NetBeans?
How can I get a single jar file with NetBeans?
When I create the project I get these files:
dist/lib/libreria1.jar
dist/lib/libreria2.jar
dist/software.jar
The libraries that have been imported to create the project are in separate folders:
libreria1/libreria1.jar
libreria2/libreria2.jar
libreria1, libreria2, dist folders are all located inside the project folder.
I added the following code to the build.xml:
<target name="-post-jar">
<jar jarfile="dist/software.jar">
<zipfileset src="${dist.jar}" excludes="META-INF/*" />
<zipfileset src="dist/lib/libreria1.jar" excludes="META-INF/*" />
<zipfileset src="dist/lib/libreria2.jar" excludes="META-INF/*" />
<manifest>
<attribute name="Main-Class" value="pacco.classeprincipale"/>
</manifest>
</jar>
</target>
Of course there is also the project folder:
src/pacco/classeprincipale.form
src/pacco/classeprincipale.java
Can you tell me what is wrong? The error message I get is as follows:
C:...\build.xml:75: Problem creating jar: archive is not a ZIP archive BUILD FAILED (total time: 2 seconds)This is not a NetBeans forum, it is a JDeveloper forum. You might want to try http://forums.netbeans.org/. I also saw your other question - try looking in the New to Java forum: New To Java
-
How to make a Java program that recognises a function of two variables...
How to make a Java program that recognises a function of two variables to assign values to that?
First I will give an example and then do the question.
Ex1.
We have any function, eg.y = x ^ 2 + 1 (read 'y' equals 'x' high to the square), a function of the second degree.
To build the graph of this function attach values to 'x' to find the values of 'y'
And thus mount the pair ordered (x, y) which represents a point on the Cartesian plane.
Assigning values to 'x' 'we can build up a table that gives us the pairs ordered:
We can use any numbers, but arfer interval [-3.3]
X | y = x ^ 2 + 1
-3 | Y = (-3) ^ 2 +1 = 10
-2 | Y = (-2) ^ 2 +1 = 5
-1 | Y = (-1) ^ 2 +1 = 2
0 | y = (0) ^ 2 +1 = 1
1 | y = (1) ^ 2 +1 = 2
2 | y = (2) ^ 2 +1 = 5
3 | y = (3) ^ 2 +1 = 10
We then ordered the pairs:
(-3.10), (-2.5); (-1.2), (0,1), (1,2), (2,5), (3,10)
Tabem that can be represented by a table:
X | y
-3 | Y = 10
-2 | Y = 5
-1 | Y = 2
0 | y = 1
1 | y = 2
2 | y = 5
3 | y = 10
Now I begin to explain my doubts.
See this program:
Ex2
* To change this template, choose Tools | Templates
* And open the template in the editor.
Encontrando_o_valor_de_y package;
* @ Author des Soldat Gottes
Import javax.swing.JOptionPane;
Public class (Main
* @ Param args the command line arguments
Public static void main (String [] args) (
Int x, y;
String x1;
X1 = JOptionPane.showInputDialog ( "We have the function y = x + 1 \ n" +
"Assign a value for 'x',"); / / receives a value for the function y = x + 1
X = Integer.parseInt (x1); / / tranforma String in int
Y = x + 1; / / receives the value of 'x' and calculates' y '
JOptionPane.showMessageDialog (null, "The value of 'y' is: \ t \ t" + y);
/ / Displays the value of 'y'
System.exit (0);
We see that the program receives above a value for 'x' and replaces the function contained in the program, y = x + 1, and so is the value of the variable 'y'.
In: x1 = JOptionPane.showInputDialog ( "We have the function y = x + 1 \ n" +
"Assign a value for 'x',");
The entry is a number and that number is assigned aa ja existing function in the (y = x + 1).
The question is: would it be possible to come to a function?
Ex: the program ask: DIGITE THE FUNCTION?
The USUARIO DIGITARIA A FUNCTION ANY, TYPE: y = x ^ 2 +1
The program would recognize the function and give numerical values to that function as Ex1, at the beginning of this text.
And then to find the values of the x and y launch a table.
It would be possible that?
By invez of entering with a number so that the program sustitua a function ja existing as Ex2, seen above, entering with a function quaquer (type: y = x ^ 2 +1) for the program atribuisse values to that function and then create a table of values as Ex1.
I hope it has been easier to understand my doubts now.
Thank you for your attention!
God bless!rafaelmenezes wrote:
Thanks for the explanation, could understand what fly said.
But as it applied to a program?
How to create a program that recognizes that the entry coefficients?Are you asking about how to parse out the coefficients from the string "3x^4 + 4x^3 - 8x^2 + 5x^1 + 2x^0"? If you define the format to strictly follow that example, this should get you started:
Strip out the spaces
Split the String on "x^"
That should give you [3, 4+4, 3-8, 2+5, 1+2, 0]
Split each resulting String on "+ | -", preserving the operator as a token so you can apply the correct sign to the coeff.
That should leave you with [3, 4, +, 4, 3, -, 8, 2, +, 5, 1, +, 2, 0]. Every other number is a coeff, the rest are the degrees.
You can strip out the +, since those coeffs are already positive, and strip out the - after negating the following number. This is all assuming that you have to write this yourself. There is no doubt already a library or 5 out there that does this for you. -
How to handle 2 or more .jar files with an applet
Hey out there
I have created an ftpClient application that uses "jakarta ftpClient". It works fine as an JFrame application � But when I converted the Application into an JApplet I get the following Exception:
java.lang.NoClassDefFoundError: org/apache/commons/net/ftp/FTPClient
I have bundled the main application into a .jar file (Application,jar). But I don't know how to handle the 2 jakarta .jar files with my JApplet??
I Tried to append the 2 jakarta .jar files to the Application,jar with the following code:
jar cvf Application.jar 1.class 2.class�. commons-net-1.4.1.jar jakarta-oro-2.0.8.jar
But with the same result / Exception (I have signed the Jar file!)
Can anyone help meHi i have a question with your application can you down- or upload more files at the same time? Because i'm having problems with my ftp application.
Here is the link with my problem maybe you can help me. I will be very pleased when you can help me.
http://forum.java.sun.com/thread.jspa?threadID=5162042&tstart=0
Thx
Satanduvel -
How to install a Application in *.jar file format?
How to install a Application in *.jar file format?
I have taken the *.jar file into the device into media folder. but device is not recognizing the file format
could some one plz provide some suggestion to proceed with this?
Thanks
Mohamed JaveedI'm having the same problem. I've put .jar into the 'system' folder but that doesn't seem to make the program work neverless see it on my device. Help.
-
How to run a java program in another folder
Hello!
I want to run for example the java class file in the path ./sourcecode/javafile.class. It works fine if I do the following:
cd sourcecode
java javafile
but it cannot work if I do:
java sourcecode/java
The error it outputs is NoClassDefFoundError.
Can someone tell me how to run a java program in another folder
thanks a lot.You need to specify the classpath using the -cp flag when running. so instead of
"java sourcecode/javafile"
Try
"java -cp sourcecode javafile" -
How i can call java program in VB2005 ?
Hi members...
Please...please...please...
If any one now how i can call java program in VB.net program and open it ,please i want now the way to do it by details and by examples and step step to do it ,,..
thanks ...If your server does not return to the command prompt, write a java programm which starts your server and returns to the command prompt.
An example for an application like this:
import java.io.IOException;
public class StartApp
public static void main(String[] args)
if (args.length > 0)
StringBuffer cmd = new StringBuffer();
for (int index = 0; index < args.length; index++)
cmd.append(args[index] + " ");
try
Runtime.getRuntime().exec(cmd.toString());
catch (IOException ioe)
System.out.println("Error: command not found: " + cmd.toString());
else
System.out.println("Error: missing arguments");
An example for starting your server with that programm:
/usr/bin/java -jar ./StartApp.jar /usr/bin/java -jar ./myServer.jar
It works. Have fun. -
How to execute a java program by clicking !?!?
Just a click to execute a java program?!!
Like the ".exe" in Windows or "x" permission in Unix ?!?!?!
How can I do that?
And how to set a java program file to display as a personal icon? (My Icon)
:-)Well this is what I do in Windows (I use XP but it works in others):
First you have to make sure all the class files are in the same folder (duh)
Then you copy your java.exe from your jre folder into the folder with all your class files.
Finally, you create a shortcut to java.exe and add your class name to the command line on the shortcut.
Now all you have to do is double click on the shortcut and your program runs. Sure it's not that pretty but it works. -
Including helper classes in java proxy jar file
I must not be using the right header search criteria because I'm sure this question
has been asked before. In a Web Service File (.jws) I've imported a couple of
helper classes that function as data transfer objects. I did this to maintain
consistency with other portions of the application. The Java Proxy jar file generated
by Workshop does not include these files. Is there a way of including these dependencies
or do I need to distribute another jar file with my helper classes?Hi Naichen,
I was able to successfully run both the autotype and clientgen Ant task, on the
WSDL you provided. The code behind those Ant tasks are pretty much what the WebLogic
Web Services test page run. Are you using WLS 8.1 SP2? If not, you might want
to try with that version.
Regards,
Mike Wooten
"Naichen Liu" <[email protected]> wrote:
>
>
>
Hi,
I am having a warning message when trying to generate java proxy jar
file on weblogic8.1
webservice test web app, the message is as follows:
"Warning Failed to generate client proxy from WSDL definition for this
service.
Prescription Please verify the <types> section of the WSDL."
in the mean time, on weblogic starting terminal, I saw the following
exceptions,
C:\DOCUME~1\u252738\LOCALS~1\Temp\wlwproxy37508.jar1533409921\com\ual\www\rcc\cb
t\schema\modifypnr\AlphaLength4Deserializer.java:36: cannot resolve symbol
symbol : class FacetUtils
location: package binding
weblogic.xml.schema.binding.FacetUtils.checkLengthFacet(__typed_obj,4L);
^
C:\DOCUME~1\u252738\LOCALS~1\Temp\wlwproxy37508.jar1533409921\com\ual\www\rcc\cb
t\schema\modifypnr\OSIFieldAnonTypeDeserializer.java:36: cannot resolve
symbol
symbol : class FacetUtils
location: package binding
weblogic.xml.schema.binding.FacetUtils.checkMaxLengthFacet(__typed_obj,69L);
^
C:\DOCUME~1\u252738\LOCALS~1\Temp\wlwproxy37508.jar1533409921\com\ual\www\rcc\cb
t\schema\modifypnr\AlphaLength2Deserializer.java:36: cannot resolve symbol
symbol : class FacetUtils
location: package binding
weblogic.xml.schema.binding.FacetUtils.checkLengthFacet(__typed_obj,2L);
^
C:\DOCUME~1\u252738\LOCALS~1\Temp\wlwproxy37508.jar1533409921\com\ual\www\rcc\cb
t\schema\modifypnr\FreeFormAnonTypeDeserializer.java:36: cannot resolve
symbol
symbol : class FacetUtils"
Can anybody help me about this issue? I attached WSDL file, also United
Airlines
got an enterprise weblogic license deal with BEA, any help will be highly
appreciated.
Thanks!!!
Naichen
Maybe you are looking for
-
CLOB Datatype (Assgin more than 32k fails)
Dear All Can anyone tell me why i am getting this error if i assign more than 32k character to clob variable in pl/sql but i can assign it from table to a variable Pl/sql 1(ORA-06502: PL/SQL: numeric or value error: character string buffer too small)
-
Hi. I'm trying to make an invoice with DI that has different discounts in its lines (not in the header's discount). I use oDoc.Lines.DiscountPercent in the apropiate line to give a % discount value but it is ignored and appears in the header's discou
-
Hello Everyone, My RSS feeds stopped working on April 12th. Two of them have given me feeds today but nothing from yesterday or the day before or the day before that. Very strange. I've tried quitting Mail, restarting my computer, control clicking on
-
How to add new product in interactive demand planning(IDP)
Hi gurus, How to add new product in interactive demand planning(IDP), can you suggest me, when i click data view in IDP, it will show new product. Regards babu
-
Examples of using lightbox to display Flash content (swf)?
I want to use lightbox to display Flash video player. I would like to have lightbox load a page that has SWFObject code for displaying the Flash content. This page with the Flash content and SWFObject will have certain paramters and vars. Does any