How do I run a java program from a different directory?

爱⌒轻易说出口 提交于 2019-12-17 18:28:59

问题


I have a java program that I would like to be able to run from anywhere on my machine. I would like to run it from my Cygwin command prompt. I've made scripts to call the java program. I added the location of the java program to the classpath, and the scripts work when I run them from the java program's directory. However, when I try to run from any other directory, I get:

java.lang.NoClassDefFoundError: commandprogram/CommandProgram

This is my script:

#!/bin/sh
CWD=`dirname "$0"`
java -cp "$CWD/classes;$CWD/lib/AJarFile.jar" commandprogram/CommandProgram

Changing the java line to the following:

java -cp "$CWD/classes;$CWD/classes/commandprogram;$CWD/lib/AJarFile.jar" CommandProgram

produces the same results.


回答1:


add your directory to classpath example:

java -classpath commandprogram CommandProgram

or

java -classpath directory_to_program Program



回答2:


After trying just about everything I could think of, I echoed out the command and saw that there was mixing of Cygwin paths and Windows paths. The solution was to change the script to:

#!/bin/sh
CWD=`dirname "$0"`
CWD=`cygpath -w "$CWD"`
java -cp "$CWD/classes;$CWD/lib/AJarFile.jar" commandprogram/CommandProgram

Then CWD changed to "C:\Program Files\..." instead of "/cygdrive/c/Program\ Files/..."

I had previously encountered this problem and solved it with the cygpath -w solution, but then changed my script slightly and didn't notice that the path problem came back.




回答3:


you have to use a dot to separate packages, not a slash.

java -cp "$CWD/classes;$CWD/lib/AJarFile.jar" commandprogram.CommandProgram




回答4:


The usual way of running a java file is to save it in the Java/Bin folder and Run cmd

C:\Program Files\Java\jdk1.7.0_05\bin> javac filename.java && java classname

If you save the file in different directory such as D:, you can use the following on the cmd prompt:

D:\Project java> set path=%path%;C:Program Files\Java\jdk1.7.0_05\bin


来源:https://stackoverflow.com/questions/1190018/how-do-i-run-a-java-program-from-a-different-directory

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