0

I'm building a java server program that connects to a psql database with JDBC drivers. I need to compile the program in a .jar file, but when I try to do so and run it, I get this exception. (the program has to run on a linux machine)

java.lang.ClassNotFoundException: org.postgresql.Driver at java.net.URLClassLoader.findClass(URLClassLoader.java:381) at java.lang.ClassLoader.loadClass(ClassLoader.java:424) at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:349) at java.lang.ClassLoader.loadClass(ClassLoader.java:357) at java.lang.Class.forName0(Native Method) at java.lang.Class.forName(Class.java:264) at Server.connectToDatabase(Server.java:53) at Server.(Server.java:33) at Main.main(Main.java:10)

Since the program works fine on IntelliJ editor, I assume that the problem is that there isn't the jdbc driver in the jar file. How can I add it?

Federico Taschin
  • 2,027
  • 3
  • 15
  • 28
  • Could you show us the output of `jar tf [jarfile]`? Especially `Main.main` and the driver file. – markspace Jun 02 '18 at 15:44
  • Possible duplicate of [How to run a Java program with external library from CLI](https://stackoverflow.com/questions/23179761/how-to-run-a-java-program-with-external-library-from-cli) – Kraylog Jun 02 '18 at 15:46
  • Add the driver jar to the classpath. Refer https://timjansen.github.io/jarfiller/javabasics/jar/libraries.xhtml – Shubham Kadlag Jun 02 '18 at 15:47
  • You need to add the driver on the classpath when executing. External dependencies (other libraries like JDBC drivers) are normally **not** included in the application Jar. If you want that you need to take additional steps (and it can lead to further complications). – Mark Rotteveel Jun 02 '18 at 15:55

1 Answers1

0

You need add PostgreDriver to your classpath and use command like following.

$Java -classpath postgre-jar+additional-jars-if-any Your-Main-class
Red Boy
  • 5,429
  • 3
  • 28
  • 41