Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 269
Arya Avatar asked Dec 04 '25 09:12

Arya


2 Answers

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~

like image 155
Stewart Murrie Avatar answered Dec 05 '25 22:12

Stewart Murrie


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
like image 39
Raghuram Avatar answered Dec 05 '25 23:12

Raghuram