Setting the classpath for JAR files - java

I have recently just created Java project using Eclipse that requires 2 JAR files (phiget21.jar and the mysql.jar)
Everything works fine when running the programme in Eclipse, and I have noticed the the jar files are saved in a 'lib' folder.
I soon going to me moving the programme off my computer to be used on other machines, so I decided to create a batch file to compile all of the classes and then run.
However, I am having trouble with the locating of the jar files. In the batch file do I require a command something like: set classpath=.:..;mysql.jar:../phidget21.jar, before the compilation of the Java classes?
I have read that the dots (...) have something to do with directories but not entirely sure how to implement them.
My programme is currently saved in these locations:
Project/src/.java files (I have also put the .jar files in here as well as i thought this may make thing s easier)
Project/lib/ .jar files
Any help would be greatly appreciated!

while setting the classpath a single dot (.) means current directory. As you jar files are in current directory, you just need to go to your current directory using cd command in DOS prompt, then use
set classpath = .;filename.jar;another filename.jar
Here . represents current directory and semicolon separates each classpaths.
You can even set classpath of more than one jar files using wild card character * which can be read as all.

You need something like
java -classpath lib/foo.jar:. com.company.Program
you can also use wildcards since java 6. see here
so the above becomes
java -classpath lib/*:. com.company.Program

Related

Running a java project in terminal with multiple .java files (multiple attempts described inside)

I have been doing a coding exercise inside the IntelliJ IDEA Community Edition 14 IDE, using OpenJDK.
The project is split over 4 .java files all in the same package.
My end goal is to run this in the terminal/bash (I use System.console().readLine() which doesnt play nicely in the IDE's console).
I've tried navigating to the directory where these 4 files reside (they all reside in the same dir) and tried:
javac -classpath . BibliotecaApp.java Book.java BookManager.java LibraryDB.java
This creates 4 corresponding .class files fine.
The Main is in bibliotecaApp.java/class, so I try run it by:
java BibliotecaApp
But I get the error
Exception in thread "main" java.lang.NoClassDefFoundError: BibliotecaApp (wrong name: com/twu/biblioteca/BibliotecaApp)
Plus about 13 lines of specifics.
Now googling this error seems to be a class path problem, and this is where I get stuck.
From places I've read, usingecho $PATH gives me:
/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games:/usr/local/games
This is still from the directory of the .java files above.
That path means nothing to me. I have no idea what it is or what it does, or what even a classpath is! Theres alot of resources out there on setting a classpath, but they aren’t helping me because I don't know what it's meant for.
That was a dead end for me. I tried to create a .jar instead using IDEA's Build Artifacts as seen HERE. It created a .jar file but when I navigate to that directory and try run it via:
java -jar biblioteca_jar
I get
Error: Invalid or corrupt jarfile biblioteca_jar
Another issue is that in the file explorer, the file actually comes out as biblioteca.jar, but ls on that dir shows biblioteca_jar. Is that normal?
The code is on my GitHub if that helps anything
https://github.com/botagar/twu-biblioteca-JohnGeddes
Based on your compiler step, change this
java BibliotecaApp
to
java -cp . BibliotecaApp
Which will add the current directory to the classpath for the java runtime environment. See also the Oracle Technote Setting the Class Path.
A jar file is a kind of zip, and should have a .jar extension. So this
java -jar biblioteca_jar
should probably be
java -jar biblioteca.jar
And you can check if the file is valid with any zip archive reader. Including jar itself,
jar tvvf biblioteca.jar
Edit
Based on your comments below,
cd ~/Documents/ThoughtWorks Uni/TWU_Biblioteca-master/src/
and then
java -cp . com.twu.biblioteca.BibliotecaApp

How to make jar files that draw from a source folder

I've been wanting to make executable jar files with java lately. When executing my code with Eclipse it works perfectly. But when I use Eclipse to export the same code as a runnable jar, Most of my jars work except the ones that draw from separate source folders.
The jar will be made but when launched it will try and open and then just say to check to console for possible errors. I try and run the jar through the console with the command "java -jar test.jar". and It says it cannot access the jar. Any Ideas? Btw Im on a macbook pro osX. Thank you!!
picture of where my files are within eclipse
If you have a file you want to store in a jar and access from there, you don't really have a Java File any more. Look at Class.getResourceAsStream() and Class.getResource() - the first can give you an InputStream to the (used-to-be) file, the second returns a URL and can be used for things like images. Note that the file being accessed can be accessed relative to the package/folder location of the class or relative to a classpath root (by putting "/" at the front of the resource name ("/resource/funny.jpg")).
When you execute the jar from a command line, be aware that you have a thing called the "default directory"; it is a folder in which your commands execute by default. If your jar is not in the default directory, you have to specify a valid folder path to your jar to execute it.

Jar file execution through use of BAT file

I have created a simple class with only inherent Java dependencies (java.io, etc).
I have set up my jar file and the bat file in the same folder. The BAT simply reads:
java -jar "MyApp.jar"
pause
I have been able to run it from several different locations on my computer. But when I sent it to a coworker as a zip file, he was unable to run it by double clicking the BAT file.
The command window came back with an error
could not find the main class: MyApp.MyApp. Program will exit.
I've poked around this site but most similar errors involve use on the same computer.
Yes the other computer has Java installed 6.29
Any help much appreciated.
Two options that I can think off the top of my head:
1) He might not have extracted them both to the same directory (or) after extraction, he might have moved around the JAR file to another location.
2) His classpath does not include the current directory. Your classpath has a '.' (indicating the current directory) while his doesn't. If that is the case, you can probably modify your command to include the '-cp' switch.
In order to run a jar that way, you need a META-INF folder inside it with a manifest file inside that. The manifest file needs a main-class line that points at your class with a main(). Your IDE probably added that, but maybe in the process of extracting things he unzipped the jar file too, or something "interesting" like that.
http://docs.oracle.com/javase/tutorial/deployment/jar/appman.html

How to set a class path in java for jexcelapi

I installed java and set path, its running successfully. Now i need is how to make use of jexcelapi. I download jexcel api and extracted it. I dono where to place the extracted file and also I dono how to set CLASSPATH for jexcel file.
Don't set the CLASSPATH variable, because it's global to all the Java programs.
Use the -classpath (or -cp) option when running java. See http://docs.oracle.com/javase/6/docs/technotes/tools/windows/classpath.html for details.
You basically only need to put the jxl.jar file in the classpath of your program. To make it easier, you can just make sure that file is in the same folder that you run your program from. It needs to be in the build path of your program, so if you use eclipse you can just add the jxl.jar file to your build path.
In eclipse, it runs things from the target or bin folder usually, so you would need to make sure the file was in that folder if you wanted to run it from the command line.
The key is just having jxl.jar by your .class file or .jar depending on how you execute your program.

The dreaded java.lang.NoClassDefFoundError

I've looked through many of the existing threads about this error, but still no luck. I'm not even trying to package a jar or use any third-party packaging tools. I'm simply running from within Eclipse (works great) and then trying to run the exact same app from the command line, in the same location it's built to (getting this error). My goal is to be able to zip up the bin folder and send it off to be run by someone else via a command line script. Some details:
It's a command-line app and I'm using the commons-lang-2.4.jar for string utilities. That is the file that cannot be located (specificaly "java.lang.NoClassDefFoundError: org/apache/commons/lang/StringEscapeUtils")
I have that jar in my lib folder and have added it to my build path in Eclipse via right-click "Build Path -> Add to Build Path"
The .classpath file looks correct and contains the reference to the jar, but I assume that file is only used by Eclipse (contains this line: <classpathentry kind="lib" path="lib/commons-lang-2.4.jar"/>)
Could this be related to the Eclipse working directory setting? I have some internal template files that I created that are under src/templates, and the only way I can seem to get those to be seen is by setting the project working directory to AppName/src. Maybe I should be putting those somewhere else?
Let me know if any additional info would help. Surely this is something simple, but I've wasted too much time on it at this point. This is reminding me why I originally left Java back in '05 or so...
A NoClassDefFoundError basically means that the class was there in the classpath during compiletime, but it is missing in the classpath during runtime.
In your case, when executing using java.exe from commandline, you need to specify the classpath in the -cp or -classpath argument. Or if it is a JAR file, then you need to specify it in the class-path entry of its MANIFEST.MF file.
The value of the argument/entry can be either absolute or relative file system paths to a folder containing all .class files or to an individual .jar file. You can separate paths using a semicolon ;. When a path contains spaces, you need to wrap the particular path with doublequotes ". Example:
java -cp .;c:/path/to/file.jar;"c:/spacy path/to/classes" mypackage.MyClass
To save the effort of typing and editing the argument in commandline everytime, use a .bat file.
Edit: I should have realized that you're using an Unix based operating system. The above examples are Windows-targeted. In the case of Unix like platforms you can follow the same rules, but you need to separate the paths using a colon : and instead of an eventual batch file, use a .sh file.
java -cp .:/path/to/file.jar:"/spacy path/to/classes" mypackage.MyClass
Are you specifying the classpath to java on the command line?
$ java -cp lib/commons-lang-2.4.jar your.main.Class
The classpath setting you are setting in Eclispe are only for the IDE and do not affect how you application is run outside the IDE. Even if you use the Eclipse Functionality to export your application as an executable jar file there is no out of the box way to package all the jars your application depends on.
If you have packaged you application into a jar file called myapp.jar then running a command like below will run the application with the jar you depend on, if you have more than one just add them separted by ; on Windows or : on Unix:
java -jar myapp.jar -cp .;c:/pathtolibs/commons-lang-2.4.jar
If you are just running the classes directly then either run the folder containing your .class files will also need to be on the path (though I assume it already is since you are able to run the program and get errors).
Consider File -> Export -> Runnable jar to create a jar file which can be invoked directly with
java -jar yourProgram.jar
There are several variants depending on your needs.
Eclipse does not move any of the jars in your classpath into the bin folder of your project. You need to copy the util jar into the bin folder. If you move it to the root of the bin folder, you might be able to get away without any classpath entries but it's not the recommended solution. See #BalusC's answer for good coverage of that.
Eclipse doesn't build executable java classes by default. Don't ask me why, but it probably has something to do with using their own tools.jar (somewhere in plugins/org.eclipse.core ?) so that Eclipse can run without a JDK.
You can usually go to your project bin directory and do:
java -cp . MyClass
But if you have external jars, Eclipse handles those internally in another weird way, so you'll need to add those too.
make sure your jar commons-lang-2.4.jar in classpath and not redudance.
I ever add jar file to my classpath, and have 2 file jar in my classpath. After I delete it, work smooth

Categories

Resources