Set default classpath to use in `java` command in

2019-01-23 21:25发布

问题:

What I'm trying to do is running a .java source by compiling and running it from command prompt (not using any IDE) using commands javac and java and the program connects with MySQL, so everytime I run the program from cmd, I need to specify path of the MySQL connector using -classpath switch of java. And entire command to run the program gets something like below:

java -class .;path/to/connector/mysql-connector.jar MySQLConnect

where I want it to be as simple as for other programs like java MySQLConnect and it should run the program.

Is there any way I can add the connector's path to environment variables of Windows that java make use of it. I already tried by creating a new CLASSPATH variable in Windows environment variables and added absolute path of the connector with file name along, but that didn't worked.

Please provide me the workaround of this Windows and Ubuntu as well.

Thanks.

回答1:

WIndows : Copy mysql-connector.jar to C:\Program Files\Java\jdk1.6.0\jre\lib\ext and copy the same file to C:\Program Files\Java\jre1.6.0\lib\ext

go to My Computer -> Properties -> Advanced -> Environment Variables

Set these paths

 JAVA_HOME  
 C:\Program Files\Java\jdk1.6.0

 PATH 
 C:\Program Files\Java\jdk1.6.0\bin;

 CLASSPATH
 .;C:\Program Files\Java\jre1.6.0\lib\ext\mysql-connector.jar;.;

open a fresh command propmpt

type
java -version press Enter



回答2:

WINDOWS

Go to My Computer -> Properties -> Advanced -> Environment Variables

then find CLASSPATH variable in System variables and click on edit to add your jar file there.

LINUX or MAC

In your shell use a variable CLASSPATH in your .bashrc or .profile to set a default class path.



回答3:

Set classpath=%classpath%;location of mysql-connector with connector file name.jar. For example:

set classpath=%classpath%;D:\TECHNICAL\JAVA WORLD\JDBC\mysql-connector-java-5.1.18-bin.jar;

D:\TECHNICAL\JAVA WORLD\JDBC\ is the location of mysql-connector.

To set this path go to Advanced System Settings->Environment variables->User variables->CLASSPATH->Edit, then type set classpath=%classpath%;D:\TECHNICAL\JAVA WORLD\JDBC\mysql-connector-java-5.1.18-bin.jar; and finally press OK.

I have done in this style. After that, I got result of programs correctly. Then there is noCLassNotFoundException.