How do I import jars into my java program? - java

I've downloaded two jars. I want to import some of their contained classes. How do I do this?
It's for my algorithms class. I've tried following the instructions on the following site to no avail.
http://algs4.cs.princeton.edu/code/
There's an installer for OSX (I'm running Mountain Lion) which allegedly adds the jars to your classpath. Unfortunately it also installs Dr. Java. I'd rather just use Sublime and Terminal. I assumed it would be easy enough just...
import java.stdlib;
in my Percolation.java file, but javac-ing that program yields a "package stdlib does not exist", as does
import stdlib;
I've added the location of stdlib.jar and algs4.jar to my Terminal CLASSPATH manually via:
export CLASSPATH=$CLASSPATH:/Users/Michael/path/to/jar/algs4.jar:/Users/Michael/path/to/jar/algs4.jar
export CLASSPATH=$CLASSPATH:/Users/Michael/path/to/jar/stdlib.jar:/Users/Michael/path/to/jar/stdlib.jar
I've also attempted
javac -cp $CLASSPATH:/Users/Michael/path/to/jar/algs4.jar:/Users/Michael/path/to/jar/stdlib.jar Percolation.java
But I still get a
javac Percolation.java
Percolation.java:1: cannot find symbol
symbol : class stdlib
location: package java
import java.stdlib;
^
Percolation.java:2: package java.algs4 does not exist
import java.algs4.WeightedQuickUnionUF;
^
What's going on here?
Also is there a way to permanently add those values to my CLASSPATH in OS X mountain lion. I have to perform that command with every new Terminal.

If you're using Terminal to compile and launch your program, then in the Terminal window, begin by setting the CLASSPATH:
$ export CLASSPATH=$CLASSPATH:/Users/Michael/path/to/jar1.jar:/Users/Michael/path/to/jar2.jar
Then you can type echo $CLASSPATH and see that the jars are referenced.
Now, in the same Terminal window, use javac to compile your class. Setting the CLASSPATH as above only applies to the current Terminal window and any processes launched from it.
Alternately you can pass the CLASSPATH to javac:
$ javac -cp $CLASSPATH:/Users/Michael/path/to/jar1.jar:/Users/Michael/path/to/jar2.jar MyClass.java
To persist this CLASSPATH for future Terminal sessions, add the export line above to the file .profile in your home directory.

It is outdated to answer this question, but maybe it will be useful for future participants of Princeton Algorithms course.
After adding CLASSPATH in environment java get classes from packages but still will generate errors on import command. You need to delete import algs4 and stdlib from source files and compilation will run smoothly.
This solution works on Ubuntu 12.04 with zsh.

You probably have the classpath stuff right. The class you're trying to import may not be called java.stdlib though. You need to import the fully qualified package name ... probably something like org.somecompany.ourlibrary.stdlib. Thus you would need
import org.somecompany.ourlibrary.stdlib
at the top of your Percolations.java file with the rest of the import statements.

Is your Percolation program contained in its own package? If so try putting it into the default package by commenting out any package statements from your files and recompiling it.
Also, nothing in algs4 is in the java package, it's all it's own separate thing.

If you're using Eclipse (as I do), select the current project, then you open the project properties from the menus. On the left you select "Java Build path", and then you select the tab libraries. Now you click the button "Add external Jars" and you point to your jar files, and you're done.
Good luck.

Launch javac with the -classpath <path_to_jar> option. Or edit the CLASSPATH environment variable so that it contains the JAR with the classes you wish to use.

I faced the same problem during work on this course, but for windows. I'll leave this comment here in case it will help somebody.
If you use DrJava you don't need any import statements in code. If you followed installation steps described in course, everything is configured for you.
But here can be a problem - it puts jar files in your current user directory, path to which can contain inappropriate symbols(russian letters in my case). You need to check it in Edit -> Preferences menu. You can see there algs4.jar and stdlib.jar paths. Make sure that this path are correct and point to real existing files.
I just moved all necessary files to another dir and changed paths in this menu. It solved this problem for me.

I wasted a lot of time with importing the class, tried the CL option of "javac -cp .;stdlib.jar mad.java" etc but used to get the same error you mentioned.
I then commented out the import altogether and made sure the DrJava's preferences had the 2 classpaths added + the %CLASSPATH% variable to have the right value. Is simply works now.
Good luck!

just name the package to default then it will work fine . also after that you dont need to import anyting just run some code provided in
Fundamentsls
chapter like
average
.

My solution was to add 2 new build systems to my Sublime text editor: one to compile and the other to execute. Use Tools->Build_system->New_build_system... from main menu with these two code snippets:
for compilation (I've named the file "algs-compile.sublime_build"):
{
"cmd": ["javac", "-cp", "/Users/admin/algs4/stdlib.jar:/Users/admin/algs4/algs4.jar:.", "$file"],
"file_regex": "^(...*?):([0-9]*):?([0-9]*)",
"selector": "source.java"
}
for running ("algs-run.sublime_build")
{
"cmd": ["java", "-cp", "/Users/admin/algs4/stdlib.jar:/Users/admin/algs4/algs4.jar:.", "$file_base_name"]
}
Don't forget to replace paths to jar-files here with the correct ones from your system.
I understand that this question is rather old but I hope this will help somebody.

If you are getting the "cannot be resolved to a type" error, and have tried adding the stdlib.jar or algs4.jar files, here is the solution:
The libraries in stdlib.jar and algs4.jar are in the "default" package. In Java, you can't access classes in the default package from a named package. If you need to use the libraries with a named package, you can use these package versions:
stdlib-package.jar and algs4-package.jar.
You can download these files here:
http://algs4.cs.princeton.edu/code/
Then you can automatically add the import:
import edu.princeton.cs.algs4.ClassName

Open your Sublime
Choose the Tools->Build System->New Build System
Add below code to the new file
This can tell the sublime to run the commands
{
"cmd": ["javac -cp /Users/yourusername/algs4/stdlib.jar:/Users/yourusername/algs4/algs4.jar:. \"$file\" && java -cp java -cp /Users/yourusername/algs4/stdlib.jar:/Users/yourusername/algs4/algs4.jar:. \"$file_base_name\""],
"shell":true,
"file_regex": "^(...*?):([0-9]*):?([0-9]*)",
"selector": "source.java"
}
Hope this can help those who are following the Algorithm Course from Princeton University

I had this same problem. Renfei Wang's solution worked for me (I don't have enough points yet to comment directly on his response).
In Sublime, navigate to Preferences: Browse Packages>JavaC.sublime_build.
Here's what mine looks like:
{
"cmd": ["javac", "-cp", "/Users/jason/Documents/lib/*:./","$file"],
"file_regex": "^(...*?):([0-9]*):?([0-9]*)",
"selector": "source.java"
}
/Users/jason/Documents/lib/*:/ lets Sublime know the location of the directory that holds my packages, so that now when I build, it loads those packages first.

Related

Using MigLayout imported from .jar

I'm usually working in Eclipse. In my program, I'm using this miglayout-4.0-swing.jar file from this source: link.
Somehere in the .jar file is class with MigLayout.
I use these imports:
import net.miginfocom.layout.Grid;
import net.miginfocom.swing.MigLayout;
//It's from the jar file.
In Eclipse i just add library:
Java Build Path -> Libraries -> Add JARs/Add external JARs -> path to miglayout-4.0-swing.jar
So in Everything working.
But I need to run it from terminal: java (I don't use packages so i use just classes from bin) but there is the problem with the .jar file, cause myMain class probably don't know where are the classes for that .jar (doesn't work the imports upper).
I tryed copy the .jar file to same directory where are the classes. Doesn't help.
What should I do to add the .jar file correctly?
Command line java command don't know where to look for the miglayout jar file. You should run in from command line like
java -cp path_to_miglayout_jar myMain
Pretty old question, but for the sake of completeness:
You need both . (current directory) and miglayout-4.0.jar to be on your classpath. You have two ways to do so. The easiest is to use -cp
In your case, you'll need to run:
java -cp "path_to_miglayout_jar/miglayout-4.0-swing.jar:." myMain
or if you work on a Windows OS:
java -cp "path_to_miglayout_jar/miglayout-4.0-swing.jar;." myMain
If unsure if you need to use a ; (colon) or a : (or whatever the OS is asking for), you can take a look at java.io.File.pathSeparator which contains the correct separator.
The other way would be to change your CLASSPATH variable.

How to compile Java program with .jar library

I can't make javac recognize an external .jar file, whose classes I'm trying to extend. I have two files in the same directory: TestConsole.java and acm.jar. I'm compiling from the same directory using the following command:
javac -classpath .:acm.jar TestConsole.java
But it seems like javac is just ignoring acm.jar. It gives me the error:
TestConsole.java:1: package acm does not exist
import acm.program;
^
Of course, acm.program is a package in acm.jar. All of the classes in acm.jar are already compiled; I just want to use them in my classes, not compile them.
What am I doing wrong?
I am running this on a Mac, and the directory structure of acm.jar appears to be valid: It contains an acm/program directory, which has ConsoleProgram.class, the only class that TestConsole extends.
javac -classpath ".:acm.jar" TestConsole.java does not work, either.
javac -cp <jar you want to include>;<jar you want to include> <source.java>
<jar you want to include> if in same directory, just name of jar will do, if not, specify full or relative paths
if more than one jars, separate with ,
replace ; with : on unix
If possible, use some IDE like Eclipse. I used to spend a lot of time on similar things, but in industry, you will hardly ever do it in this fashion.
Are you running these commands on a Windows machine? On Windows, the elements of the classpath are separated by a semicolon, not a colon. So:
javac -classpath .;acm.jar TestConsole.java
Another possibility: the structure of acm.jar is wrong. It's not sufficient that the class files inside were compiled from files that declare package acm.program - the package structure must also be represented as a directory hierarchy, so acm.jar must contain a directory acm, and within that a subdirectory program that contains the actual class files for the classes used in TestConsole.
Check list:
your classes in acm.jar appear as:
acm/program/CLASSX.class
acm/program/CLASSY.class
when decanted with jar tf acm.jar
You're importing them like:
import acm.program.CLASSX ;
or
import acm.program.* ;
Whoever is trying to compile and still having the problem as I struggled for hours, I tried all the answers above and still was not able to run the program due to one minor issue.
The no-brainier issue was the semi colon after every package. I am not sure about Mac or Linux but for Windows Command Prompt this was the case
javac -cp mysql-connector-java-8.0.12.jar; Testing.java
java -cp mysql-connector-java-8.0.12.jar; Testing
You might wanna follow this both cases either in compilation or while running.
Many years behind but i struggled with this syntax, this worked for me to add all jar files plus compile with all classes in the program to the main class
My File Tree:
Store classes .java files
jars .jar files
images .PNG files
command line:
C:\Store>javac -cp "jars/" classes/.java classes/storeMain.java
I'm just adding for folks who are still looking for the answer to the same problem after successful compilation.
While compiling use the command as suggested above by #Michael Borgwardt:
javac -classpath .;acm.jar TestConsole.java
For executing also you need to specify the class path:
java -classpath .;acm.jar TestConsole

How can I find a package?

In my code I have the following statement import com.apple.dnssd.*; and compiler (javac) complains about this line. It writes that the package does not exist. But I think that it could be that "javac" search the package in a wrong place (directory). In this respect I have two questions:
How can I know where javac search for the packages?
I think that it is very likely that I have the above mentioned package but I do not know where it is located. What are the typical place to look for the packages?
ADDED:
On another Windows machine I tried the same thing and the "javac" does not complain (as before I compiled without any options like "-cp"). I check values of the "classpath" environment variable. It is equal to "C:\Program Files\Java\jdk1.6.0_18\bin;.;..". I went to the first classpath directory and did not find there something that could be the "com.apple.dnssd" library (no jar files, no files containing "apple"). So, I do not understand why javac do NOT complain on the second Windows machine.
ADDED 2:
On the machine #2 I have installed Bonjour after JDK. On the machine #1 JDK was installed after Bonjour.
ADDED 3:
On the machine #1 (where I cannot import the package) I found the jar file (it is located in "C:\Program Files\Bonjour" and its name is "dns_sd.jar"). I tried to add the above mentioned directory to the PATHCLASS environment variable on Windows 7 (and I restarted the system). It does not help. I still cannot import the package. I also tried to specify the "-classpath" in the command line. It also does not help. Now I will try to reinstall Bonjour (as it was advised).
ADDED 4:
I have uninstall Bonjour and Bonjour SDK. I have reload Window. Then I have installed Bonjour and Bonjour SDK. I have reload the Window. It did not solve the problem. I still cannot import the package (javac writes that package does not exist). I have also copied the *.jar file to the same directory there the source is located. It does not work. I used "javac -cp .". It does not work. Now I am out of options. I do not know what else can I try. Can anybody help me pleas?
ADDED 5:
My classpath is: C:\Program Files\Java\jdk1.6.0_18\bin;.;..;"C:\Program Files\Bonjour"
I try to compile from this directory: C:\Users\myname\java\bonjour\example
I compile by the following command: javac ServiceAnnouncer.java
I get the following error message: ServiceAnnouncer.java:1: package com.apple.dnssd does not exist
ADDED 6:
Finally I have managed to import the library. I did it in the following way:
javac -cp "C:\Program Files\Bonjour\dns_sd.jar" ServiceAnnouncer.java
The important thing is that I have specified the jar file after the -cp (not the directory where the jar file is located). It works also if I replace "dns_sd.jar" by "*". So, my conclusion is that after the "-cp" I need to specify jar files (not directories).
Java/javac will search for classes in the classpath.
The default classpath covers the /path/to/jre/lib and /path/to/jre/lib/ext folders. Any classes and JAR files which are found there will be taken in the classpath. You can in theory put your classes and JAR files there so that you don't need to do anything to get java/javac to find them. But this is actually an extremely bad practice. It's recipe for portability trouble, because this isn't the same in all machines. Leave those folders intact.
Then there's the environment variable %CLASSPATH% wherein you can specify full paths to root folders where classes are located and/or full paths to JAR files (including the JAR file name itself!). Multiple paths are in Windows to be separated by semicolon ; and in *Nix by colon :. Paths with spaces inside needs to be quoted with "". Here's an example:
SET CLASSPATH = .;/path/to/File.jar;"/spacy path to some pkg/with/classes"
Note the period . at the beginning of the argument. This indicates the current path (the current working directory from where the java/javac command is to be executed). It will only find classes in the current path that way, and thus not JAR files! You need to specify full path for them. Since Java 1.6 you can also use wildcards to specify multiple JAR files in some path. E.g.
SET CLASSPATH = .;/path/to/all/jars/*;"/spacy path to some pkg/with/classes"
This environment variable is actually a convenience way to manage the classpath so that you don't need to type the same thing down again and again in the command console everytime. But this is only useful for new-to-java users and the cause of all future confusion because they will think that this is "the" classpath. This assumption is actually wrong and again the cause of portability trouble because this isn't the same in all machines.
The right way to define the classpath is using the -cp or -classpath argument wherein you actually specify the same information as you'd like to enter for %CLASSPATH%, i.e. (semi)colon separated and paths-with-spaces quoted, for example:
javac -cp .;/path/to/File.jar;"/spacy path to some pkg/with/classes" Foo.java
Note that when you use either -cp or -classpath (or -jar) arguments, then java/javac will ignore the %CLASSPATH% environment variable (which is actually a Good ThingTM).
To save the time in retyping the same again and again, just create a bat or cmd file (or if you're on *Nix, a sh file). Basically just put therein the same commands as you'd enter "plain" in the console and then execute it the usual platform specific way.
To save more time, use an IDE. The classpath which is to be used during both compiletime and runtime inside the IDE is called the "build path". Explore the project properties and you'll see.
http://java.sun.com/javase/6/docs/technotes/tools/windows/classpath.html
To answer your first question (How to know where javac searches for packages):
Check what your $CLASSPATH variable is set to.
echo $CLASSPATH
This is where you JRE will search for class files and resources. You can either set it as an environment variable,
set CLASSPATH=path1;path2 ...
or set it when your run javac.
C:> javac -classpath C:\java\MyClasses src_dir
(Great examples for javac are found here)
In this case, your jar file containing 'com.apple.dnssd.*' should be located in your classpath. Just download that jar, and put it in the place where your classpath is searching.
Assuming that dns_sd.jar is installed in 'C:\Program Files\Bonjour', then try to compile your code like this:
cd C:\Users\myname\java\bonjour\example
javac -classpath C:\Program Files\Bonjour ServiceAnnouncer.java
This link suggests that the JAR containing this package is part of Bonjour for Windows. Look for it there.
javac.exe only searches where you tell it with the CLASSPATH. If you don't understand how to set CLASSPATH, I'd recommend reading something like this.

How to compile a .java file in Java?

I have the following code generated by Eclipse (.java file).
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.Display;
public class HelloWorldSWT {
/**
* #param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
Display display = new Display();
Shell shell = new Shell(display);
shell.setText("Hello world!");
shell.open();
while (!shell.isDisposed()) {
if (!display.readAndDispatch()) display.sleep();
}
display.dispose();
}
}
Now I want to compile the above file from the command line. I went to the directory where the source code is located and I tried two commands:
1. javac HelloWorldSWT.java
2. javac -d /home/myname/workspace/ HelloWorldSWT.java
In both cases I have the same error "The import org.eclipse cannot be resolved".
/home/myname/workspace/ - is the directory where the class file is located.
As far as I understand the compiler does not see the org.eclipse.swt package. Why?
Can it be because the problematic package is located in "/home/myname/workspace/org.eclipse.swt/" (not in "/home/myname/workspace/org/eclipse/swt/")?
You need to set your classpath so that the Java compiler knows where to find the org.eclipse.* classes. You can do that with a command line switch or an environment variable.
Ok, Stephen C
I did this job by hand.
I used only Notepad++ (I promise)
Start Notepad++ and create file HelloWorldSWT.java
Copy example from author
Save it!
Open cmd and go to the directory with HelloWorldSWT.java
Run the command javac HelloWorldSWT.java
Ok, go to the Eclipse directory and find the correct jar swt-3.4.2-win32-win32-x86.jar
Run this again
D:\workspaces\spf_workspace\hand-made>javac -cp "D:\Program files\eclipse3_5\plugins\org.eclipse.swt.win32.win32.x86_3.5.1.v3555a.jar" HelloWorldSWT.java
All process take 2 minutes.
Don't try to run this:
`D:\workspaces\spf_workspace\hand-made>java -cp "D:\Program files\eclipse3_5\plugins\org.eclipse.swt.win32.win32.x86_3.5.1.v3555a.jar;." HelloWorldSWT`
Note: I add current dir . to classpath too.
Since you are doing Eclipse RCP development, you should let Eclipse handle your compilation as well. (You will most likely find your classes in a "build" or "bin" directory in the project).
In addition to compilation, there will be some "packaging" steps to create the final application, and Eclipse has tools for that, too.
If you really want to build outside of Eclipse, you need to manage a potentially large list of dependencies (such as org.eclipse.swt.widgets), which makes a pure javac unfeasible. You would need to look at Ant or Maven.
Also note that you will need the classpath to include dependencies not only for compilation, but also when you run the program.
But I though that I specify the
"classpath" during the compilation
(using -d option). I though that after
the "-d" option I put the name of
directory where all my packages are
located. Do I understand that wrongly?
try
javac -help
to see what the different command line options do. also note the other post above that explains this.
compiling from the command line and setting up classpath and everything right is a pain. however, it is useful to do it so that you understand what the ide actually does when it automates this for you.
The classpath variable or command line switch needs to point to where the org.eclipse.swt.widgets.Shell class resides, if this class is inside a jar file, then the classpath needs to contain the actual jar file,
i.e. javac -classpath /root/to/jar/eclipse.jar
Otherwise, if the org.eclipse.swt.widgets.Shell class is just a loose class file (which I doubt, I assume it will be inside one of the eclipse jar files, which you can list using jar -tvf jar-you-think-it-might-be-in.jar)...then you will need the javac -classpath to point to the location of the top level directory within the org/eclipse/swt/widgets/ path.
#Roman - this problem is too complicated for a beginner to try to address. The problem is that SWT has complicated dependencies, including dependencies on native code libraries.
You are best off running your SWT application using Eclipse "RunAs" ... or trying to find some Eclipse-specific documentation on running SWT-based applications from the command line.
You forgot about classpath

Why Java could not find the main class?

I have just copied Key-Listener code from http://java.sun.com/docs/books/tutorial/uiswing/examples/events/KeyEventDemoProject/src/events/KeyEventDemo.java. I was able to compalie it with the "javac" command. But when I try to execute the compiled code (typing "java KeyEventDemo") I have a large message in the end of which I see:
Could not find the main class: KeyEventDemo. Program will exit.
Yesterday I had a similar problem on Windows Vista (now I am on Ubuntu). In the Windows I was able to solve the problem by typing "java -cp . ProgramName" or alternatively by adding new values ("." and "..")to the environment variable "classpath".
On Ubuntu the first solution does not work. I mean, when I type "java -cp . KeyEventDemo" I still have the problem. Moreover, on Ubuntu I was able to run other programs just typing "java ProgramName".
So, can anybody tell me what is special about this KeyEventDemo? Why it does not wont to work and how it can be solved?
The class KeyEventDemo is in a package events To run it, you must be in the parent folder of the events folder that contains the class, and run it using its fully qualified name, including the package:
java events.KeyEventDemo
The classpath must contain the folder (or JAR) that's the root of the folder hierarchy that represents the packages; the current folder is (I believe) included automatically.
This program is not in the default package, but in the package "events": use java -cp . events.KeyEventDemo from the directory containing the folder "events":
+work
+events
-KeyEventDemo.class
It is because the KeyEvent class is in package events.
You either have to remove the package events; line from source code, or compile it with:
javac -d . KeyEventDemo.java
Perhaps you compile and run with diferent java version.
This is common when you try to execute an example at eclipse.

Categories