Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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.

like image 360
Swoogan Avatar asked Jul 27 '09 19:07

Swoogan


People also ask

How do I change the directory of a file in Java?

File provides methods like createNewFile() and mkdir() to create new file and directory in Java. These methods returns boolean, which is the result of that operation i.e. createNewFile() returns true if it successfully created file and mkdir() returns true if the directory is created successfully.

How do I change directory in Java terminal?

To change directories, use the cd command with the name of a directory. To return to the previous directory, use the cd command, but this time followed by a space and two periods. mkdir: To create a new directory, use the command mkdir.


2 Answers

add your directory to classpath example:

java -classpath commandprogram CommandProgram

or

java -classpath directory_to_program Program
like image 122
woakas Avatar answered Sep 28 '22 04:09

woakas


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.

like image 29
Swoogan Avatar answered Sep 28 '22 05:09

Swoogan