How to run java class file which is in different directory?

It's time for you to read on about classpath ( a way to tell java compiler where to look for the class file you intend to run ). Basically there are two ways to set classpath

  1. a environment variable CLASSPATH having ':' separate directories in unix and ';' separated directories in windows
  2. -classpath or -cp command line arg to javac command

Refer and read the below links completely
http://docs.oracle.com/javase/7/docs/technotes/tools/windows/classpath.html


Set your class path for this java file:

java -cp C:\hello\build\classes com.javahowto.test.HelloWorld 

or using Environment variables and run it from any third location from that machine.


In my program com.bsoft.conc is a package name where my class file for the compiled program will be stored.If I have to run that from home folder we have to specify java -classpath test\src com.bsoft.conc."class-file-name"

This is because we need to tell the JVM where it has to look for class file.

so , we have to specify navigation to the src using "test\src" and then class file location "com.bsoft.conc.class-file-name"

If you have set environment variable in advanced settings then it will also be overriden if you specify classpath in cmd


I had a similar problem where I was trying to run a Java program that calls a method in a class that is in another directory. I read this page and added the directory to my classpath, but I made the mistake of using '~' which in Bash means '/home/user/'.

So this command did NOT work

java -classpath ~/CurrentDirectory:OtherDirectory program

But this command did

java -classpath /home/user/CurrentDirectory:OtherDirectory program

Tags:

Java

Class