How will I include a Java jar file when compiling a Java class and running the Java file from the command console?

痴心易碎 提交于 2019-12-10 10:46:17

问题


I have a small Java file interacting with a postgresql database, so I've downloaded the drivers and in my file I import org.postgresql.Driver.

In the command console I type javac Myfilename.java ; then it compiles I run java Myfilename and it throws an error saying it can not find the org.postgresql.Driver files.

So how do I import the jar when I run the file or when I compile the file not sure when the import should take place?


回答1:


Compile:

javac -cp ".:postresql.jar" -d . MyFileName.java

Run:

java -cp ".:postresql.jar" MyFileName



回答2:


You need to add the driver jar to your build path while running.




回答3:


you need to list the filepaths of the included drivers

javac -cp "filepath.jar" MyFileName.java



回答4:


Either you can the environment variable CLASSPATH and append the jars to this CLASSPATH variable or you can use java -cp or java -classpath to run your code.

javac -classpath C:\java\postresql.jar MyClass.java or javac -cp C:\java\postresql.jar MyClass.java



来源:https://stackoverflow.com/questions/10954207/how-will-i-include-a-java-jar-file-when-compiling-a-java-class-and-running-the-j

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!