如何在Java中设置类路径?

时间:2011-03-02 19:41:24

标签: java jar classpath

我有很多jar文件要添加到我的类路径中,所以每当我编译我的java文件时,我最终会得到这样的命令:

javac -cp commons-digester-2.1/commons-digester-2.1.jar:lucene-core-3.0.3.jar:commons-logging-1.1.1/commons-logging-1.1.1.jar:commons-beanutils-core-1.7.0.jar:. CollectionIndexer.java

我试过用:

set CLASSPATH=commons-digester-2.1/commons-digester-2.1.jar:lucene-core-3.0.3.jar:commons-logging-1.1.1/commons-logging-1.1.1.jar:commons-beanutils-core-1.7.0.jar:.

然后:

javac CollectionIndexer.java

但是罐子根本没有添加:由于丢失的罐子我得到错误... 感谢

6 个答案:

答案 0 :(得分:3)

尝试使用export CLASSPATH=...代替set CLASSPATH=...

(我假设您使用的是某些描述的Unix框,给定了类路径中的冒号。)

答案 1 :(得分:1)

在我看来,最无痛的方法是创建包含所有项目相关jar的批处理文件...一个用于编译,另一个用于运行: -

<强>的compile.bat

javac -cp commons-digester-2.1/commons-digester-2.1.jar:lucene-core-3.0.3.jar:commons-logging-1.1.1/commons-logging-1.1.1.jar:commons-beanutils-core-1.7.0.jar:. %1

<强>的run.bat

java -cp commons-digester-2.1/commons-digester-2.1.jar:lucene-core-3.0.3.jar:commons-logging-1.1.1/commons-logging-1.1.1.jar:commons-beanutils-core-1.7.0.jar:. %1

有了这个,你可以这样做: -

compile.bat CollectionIndexer.java

run.bat CollectionIndexer

更好的是,您可以将它们组合在一起: -

<强> compilerun.bat

确保将“.java”附加到javac的%1

javac -cp commons-digester-2.1/commons-digester-2.1.jar:lucene-core-3.0.3.jar:commons-logging-1.1.1/commons-logging-1.1.1.jar:commons-beanutils-core-1.7.0.jar:. %1.java
java -cp commons-digester-2.1/commons-digester-2.1.jar:lucene-core-3.0.3.jar:commons-logging-1.1.1/commons-logging-1.1.1.jar:commons-beanutils-core-1.7.0.jar:. %1

有了这个,你可以这样做: -

compilerun.bat CollectionIndexer

我比设置classpath更喜欢这种方法,因为每次打开终端时我都不需要重新键入类路径。 :)

答案 2 :(得分:1)

顺便说一句,修改CLASSPATH环境变量专门用于编译项目并不是很好,因为在此之后,所有其他项目都将继承此更改。这当然只有在全球范围内改变它时才会出现。如果您不是,而是计划编写一个小脚本来构建项目,为什么不考虑使用ant?祝你好运!

答案 3 :(得分:1)

您已设置CLASSPATH,但未将其放入环境中。所以它是一个变量,但不是一个环境变量。

要将脚本/会话内变量提升为环境变量,请使用命令export,如此

export CLASSPATH

这会将变量提升为环境变量(任何继承环境的shell都可以访问它)。

某些系统允许组合和导出。在这样的系统中,您可以将set命令与export命令组合使用,如下所示:

export CLASSPATH=<your value here>

java命令只读取环境变量CLASSPATH。它不能查看非环境变量,因为它们不是从过程到过程继承的。

答案 4 :(得分:0)

除了导出UNIX环境外,还要使用绝对路径。例如,类路径条目:commons-digester-2.1 / commons-digester-2.1.jar只有在commons-digester-2.1安装目录的父目录中才有效。

在unix上,应该有一个安装软件包的公共位置。像/ usr / local,/ usr / lib或/ usr / local / lib。

答案 5 :(得分:0)

也许你想尝试使用maven来构建你的应用程序? 这很容易设置,它消除了依赖管理的所有问题。

也可以从java 6中在classpath中使用通配符: 设置CLASSPATH = my_libs \ *;