Adding jar in classpath in java

What is a classpath and how do I set it?

When programming in Java, you make other classes available to the class you are writing by putting something like this at the top of your source file:

import org.javaguy.coolframework.MyClass; 

Or sometimes you ‘bulk import’ stuff by saying:

import org.javaguy.coolframework.*; 

So later in your program when you say:

MyClass mine = new MyClass(); 

The Java Virtual Machine will know where to find your compiled class.

It would be impractical to have the VM look through every folder on your machine, so you have to provide the VM a list of places to look. This is done by putting folder and jar files on your classpath.

Before we talk about how the classpath is set, let’s talk about .class files, packages, and .jar files.

First, let’s suppose that MyClass is something you built as part of your project, and it is in a directory in your project called output . The .class file would be at output/org/javaguy/coolframework/MyClass.class (along with every other file in that package). In order to get to that file, your path would simply need to contain the folder ‘output’, not the whole package structure, since your import statement provides all that information to the VM.

Now let’s suppose that you bundle CoolFramework up into a .jar file, and put that CoolFramework.jar into a lib directory in your project. You would now need to put lib/CoolFramework.jar into your classpath. The VM will look inside the jar file for the org/javaguy/coolframework part, and find your class.

Читайте также:  Background size css border

So, classpaths contain:

How do you set your classpath?

The first way everyone seems to learn is with environment variables. On a unix machine, you can say something like:

export CLASSPATH=/home/myaccount/myproject/lib/CoolFramework.jar:/home/myaccount/myproject/output/ 

On a Windows machine you have to go to your environment settings and either add or modify the value that is already there.

The second way is to use the -cp parameter when starting Java, like this:

java -cp "/home/myaccount/myproject/lib/CoolFramework.jar:/home/myaccount/myproject/output/" MyMainClass 

A variant of this is the third way which is often done with a .sh or .bat file that calculates the classpath and passes it to Java via the -cp parameter.

There is a «gotcha» with all of the above. On most systems (Linux, Mac OS, UNIX, etc) the colon character (‘:’) is the classpath separator. In windowsm the separator is the semicolon (‘;’)

So what’s the best way to do it?

Setting stuff globally via environment variables is bad, generally for the same kinds of reasons that global variables are bad. You change the CLASSPATH environment variable so one program works, and you end up breaking another program.

The -cp is the way to go. I generally make sure my CLASSPATH environment variable is an empty string where I develop, whenever possible, so that I avoid global classpath issues (some tools aren’t happy when the global classpath is empty though — I know of two common, mega-thousand dollar licensed J2EE and Java servers that have this kind of issue with their command-line tools).

In python there’s a folder called Lib where you can store any module to use at any time with a simple import statement. Is this different than setting the CLASSPATH environment variable to a directory for third-party java packages? Even though it would be global, there would be no need to change the variable, other than adding more packages.

Nice answer, but for the dummies out here: Why do you not need to use the -cp command for every new class you create? This surely is solved automatically by your system right? But how? I sometimes encounter a problem where «something» can not be found in my classpath — I guess it is so because I didn’t add it to the cp, but why does such an error occur only sometimes instead of always? I ask this because, to be honest, I didn’t ever include anything manually with the -cp command and would not know what to do with an error like that

@Vic The classpath needs to contain the directory above the directory hierarchy corrresponding to the package name. So if I have org.javaguy.coolfw , with corresponding directory structure /path/to/org/javaguy/coolfw/ , the classpath would need to contain /path/to/ . If I add a new package org.javaguy.hotfw in the same project, the resulting class (usually) ends up at /path/to/org/javaguy/hotfw/ . This requires the classpath to contain /path/to/ , which it already does. So the new package (and classes contained therein) don’t require new additions to the classpath.

@Vic For a more concrete example and explanation, see Mastering the Java CLASSPATH (per KNU’s excellent comment)

Think of it as Java’s answer to the PATH environment variable — OSes search for EXEs on the PATH, Java searches for classes and packages on the classpath.

except that path is Completely Optional while classpath is mandatory—Java has no support for absolute names.

Not every OS searches for necessarily EXEs. This answer can be made better by changing «EXEs» to «executable binaries».

The classpath is one of the fundamental concepts in the Java world and it’s often misunderstood or not understood at all by java programmes, especially beginners.

Simply put, the classpath is just a set of paths where the java compiler and the JVM must find needed classes to compile or execute other classes.

Let’s start with an example, suppose we have a Main.java file thats under C:\Users\HP\Desktop\org\example ,

package org.example; public class Main < public static void main(String[] args) < System.out.println("Hello world"); >> 

And Now, suppose we are under C:\ directory and we want to compile our class, Its easy right, just run:

javac .\Users\HP\Desktop\org\example\Main.java 

Now for the hard question, we are in the same folder C:\ and we want to run the compiled class.

Despite of what you might think of to be the answer, the right one is:

java -cp .\Users\HP\Desktop org.example.Main 

I’ll explain why, first of all, the name of the class that we want ro tun is org.exmaple.Main not Main, or Main.class or .\users\hp\desktop\org\example\Main.class ! This is how things works with classes declared under packages.

Now, we provided the name of the class to the JVM (java command in this case), But how it (JVM) will know where to find the .class file for the Main class? Thats where the classpath comes into picture. Using -cp flag (shortcut for -classpath), we tell the JVM that our Main.class file will be located at C:\users\hp\Desktop .. In fact, not really, we tell it to just go to the Desktop directory, and, because of the name of the class org.example.Main, the JVM is smart and it will go from Desktop to org directory, and from org to example directory, searching for Main.class file , and it will find it and it will kill it, I mean, it will run it 😀 .

Now lets suppose that inside the Main class we want to work with another class named org.apache.commons.lang3.StringUtils and the latter is located in a jar file named commons-lang3-3.10.jar thats inside C:\Users\HP\Downloads . So Main.java will look like this now:

package org.example; import org.apache.commons.lang3.StringUtils; public class Main < public static void main(String[] args) < System.out.println("Hello world"); System.out.println(StringUtils.equals("java", "java")); //true >> 

How to compile the Main.java if we are always inside C:\ ? The answer is:

javac -cp .\Users\HP\Downloads\commons-lang3-3.10.jar .\Users\HP\Desktop\org\example\Main.java 
  • .\Users\HP\Desktop\org\example\Main.java is because our .java file is there in the filesystem.
  • -cp .\Users\HP\Downloads\commons-lang3-3.10.jar is because the java compiler (javac in this case) need to know the location of the class org.apache.commons.lang3.StringUtils, so we provided the path of the jar file, and the compiler will then go inside the jar file and try to find a file StringUtils.class inside a directory org\apache\commons\lang3 .

And if we want to run the Main.class file, we will execute:

java -cp ".\Users\HP\Desktop\;.\Users\HP\Downloads\commons-lang3-3.10.jar" org.example.Main 
  • org.example.Main is the name of the class.
  • «.\Users\HP\Desktop\;.\Users\HP\Downloads\commons-lang3-3.10.jar» are the paths (separated by ; in Windows) to the Main and StringUtils classes.

Источник

How to Add JAR file to Classpath in Java?

JAR is an abbreviation of JAVA Archive. It is used for aggregating multiple files into a single one, and it is present in a ZIP format. It can also be used as an archiving tool but the main intention to use this file for development is that the Java applets and their components(.class files) can be easily downloaded to a client browser in just one single HTTP request, rather than establishing a new connection for just one thing. This will improve the speed with which applets can be loaded onto a web page and starts their work. It also supports compression, which reduces the file size and the download time will be improved.

Methods: JAR file can be added in a classpath in two different ways

Method 1 – Using Eclipse IDE

Step 1: Right-Click on your project name

Step 2: Click on Build Path

Step 3: Click on configure build path

Step 4: Click on libraries and click on “Add External JARs”

Step 5: Select the jar file from the folder where you have saved your jar file

Step 6: Click on Apply and Ok.

Method 2 – Using the command line

Command 1: By including JAR name in CLASSPATH environment variable

CLASSPATH environment variable is not case-sensitive. It can be either Classpath or classpath which is similar to PATH environment variable which we can use to locate Java binaries like javaw and java command.

Command 2: By including name of JAR file in -a classpath command-line option

This option is viable when we are passing –classpath option while running our java program like java –classpath $(CLASSPATH) Main. In this case, CLASSPATH shell variable contains the list of Jar file which is required by the application. One of the best advantages of using classpath command-line option is that it allows us to use every application to have its own set of JAR classpath. In other cases, it’s not available to all Java program which runs on the same host.

Command 3: By including the jar name in the Class-Path option in the manifest

When we are running an executable JAR file we always notice that the Class-Path attribute in the file inside the META-INF folder. Therefore, we can say that Class-Path is given the highest priority and it overrides the CLASSPATH environment variable as well as –classpath command-line option. Henceforth, we can deduce that its a good place to include all JAR files required by Java Application.

Command 4: By using Java 6 wildcard option to include multiple JAR

From Java 1.6+ onwards we can use a wildcard for including all jars in a directory to set classpath or else to provide Java program using classpath command-line option. We can illustrate the Java command example to add multiple JAR into classpath using Java 6 wildcard method as follows,

java.exe -classpath D:\lib\*Main

In this method, we include all JAR files inside ‘D:\lib’ directory into the classpath. We must ensure that syntax is correct. Some more important points about using Java 6 wildcard to include multiple JAR in classpath are as follows:

Whenever JAR and classfile are present in the same directory then we need to include both of them separately

Java -classpath /classes: /lib/*

In Java 6 wildcard which includes all JAR, it will not search for JARs in a subdirectory.

Wildcard is included in all JAR is not honored in the case when we are running Java program with JAR file and having Class-Path attribute in the manifest file. JAR wildcard is honored when we use –cp or –classpath option

Command 5: Adding JAR in ext directory example be it ‘C:\Program Files\Java\jdk1.6.0\jre\lib\ext’

By using the above method we can add multiple JAR in our classpath. JAR from ext directory can be loaded by extension Classloader. It has been given higher priority than application class loader which loads JAR from either CLASSPATH environment variable or else directories specified in –classpath or –cp

Источник

Оцените статью