如何将jar导入我的java程序? [英] How do I import jars into my java program?

查看:260
本文介绍了如何将jar导入我的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/

OSX有一个安装程序(我正在运行Mountain Lion)据称将罐子加入你的类路径。不幸的是,它还安装了Java博士。我宁愿只使用Sublime和Terminal。我认为这很简单......

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;

但是javac-ing该程序产生包stdlib不存在,以及

in my Percolation.java file, but javac-ing that program yields a "package stdlib does not exist", as does

import stdlib;

我通过以下方式手动将stdlib.jar和algs4.jar的位置添加到终端CLASSPATH:

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

我也尝试过

javac -cp $CLASSPATH:/Users/Michael/path/to/jar/algs4.jar:/Users/Michael/path/to/jar/stdlib.jar Percolation.java

但我仍然得到一个

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;
             ^

这里发生了什么?

还有一种方法可以将这些值永久地添加到OS X山狮的CLASSPATH中。我必须在每个新终端上执行该命令。

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.

推荐答案

如果您使用Terminal编译并启动程序,那么在终端窗口中,首先设置 CLASSPATH

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

然后你可以输入 echo $ CLASSPATH 并看到罐子被引用。

Then you can type echo $CLASSPATH and see that the jars are referenced.

现在,在同一个终端窗口中,使用javac编译你的类。如上所述设置 CLASSPATH 仅适用于当前的终端窗口以及从中启动的任何进程。

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.

或者你可以将 CLASSPATH 传递给javac:

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

要为将来的终端会话保留此 CLASSPATH ,请将上面的 export 行添加到文件中主目录中的 .profile

To persist this CLASSPATH for future Terminal sessions, add the export line above to the file .profile in your home directory.

这篇关于如何将jar导入我的java程序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆