Compile and Run java program in linux with path to the .java file and path to external jars

4.2k views Asked by At

Yesterday I solved a problem with an answer here on stackoverflow. But I ended up with another problem, I will try to be clear:

I have a project folder in the /home/demo/Desktop/xlsToCsv/ directory where inside of it is the java file "xlsToCsv.java" and another directory with the external jars that I need in /home/demo/Desktop/xlsToCsv/jars.

Now I need to compile and run my program. Yesterday I ran a command that assumed that I was already inside of /home/demo/Desktop/xlsToCsv/, and the commands were:

javac -cp ".:./jars/*" xlsToCsv.java

java -cp ".:./jars/*" xlsToCsv

The problem was solved and I was able to run my program without any problems. But, my program was supposed to run from the root directory, ie, the directory where it is when I open the linux terminal without the need to make a "cd" command.

So, when I open the terminal the path to the .java file is:

/home/demo/Desktop/xlsToCsv/

And the path to jars folder is:

/home/demo/Desktop/xlsToCsv/jars/*

Can someone explain to me what I have to do, and the reason so? Because more that run the program, I want to know the reasons and understand the classpath mechanism in java.

1

There are 1 answers

6
Mr. D On BEST ANSWER

Avoid using relative classpath. and instread of "./jars/" use the absolute path "/home/demo/Desktop/xlsToCsv/jars/"

EDIT:

javac -cp "/home/demo/Desktop/xlsToCsv/jars/*" /home/demo/Desktop/xlsToCsv/xlsToCsv.java

java -cp "/home/demo/Desktop/xlsToCsv/:/home/demo/Desktop/xlsToCsv/jars/*" xlsToCsv