简体   繁体   中英

Running a java program in linux terminal with -class path

I've been trying for an hour to run the following program with a the postgresql classpath

class Test{
  public static void main(String[] args){
        try {
            Class.forName("org.postgresql.Driver");
        } catch (ClassNotFoundException cnfe) {
            System.err.println("Couldn't find Postgresql driver class!");
        }
  }
}

The program compiled fine with the javac command, but I'm having a hard time running it with the postgresql classpath. I have "postgresql-9.0-801.jdbc4.jar" in the same directory as the file and I tried the following, but non of them worked

java -classpath ./postgresql-9.0-801.jdbc4.jar Test
java -classpath postgresql-9.0-801.jdbc4.jar Test
java -classpath "postgresql-9.0-801.jdbc4.jar" Test

What am I doing wrong?

Regards!

When you specify the classpath you need to make sure it includes ALL of the class files your application needs, including the ones you create yourself. Assuming that Test.class is in the current directory along with the postgres Jar file, you need something like:

java -classpath postgresql-9.0-801.jdbc4.jar:. Test

See the Java Glossary for more details.

bm~

What is the error? ClassNotFoundException for Test or the postgres library? If former, it is because you need to add Test in your classpath as well.

Assuming you are in the same directory where Test.class and the postgres jar is present,

java -classpath .:postgresql-9.0-801.jdbc4.jar Test
command :java -cp .;postgresql-9.0-801.jdbc4.jar Test

both the jar and the class are in the same directory from which the command is run
Also make your class definition as public !!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM