In this article we are going to explain how to read a file from class path. But firstly we need to know what classpath is, and why would we do something like that.
So the classpath is a parameter in the JVM (Java Virtual Machine) that specifies the location of user-defined classes and packages. Basically that can be explained like a direction. Everyone of us had a situation when we needed a direction, we knew what we were looking for but didn't knew where to look for it (whatever the "it" is) , well Java is no different, when Java need a direction where to find class libraries, Classpath can provide that information.
Overview of Classpath
Similar to the classic dynamic loading behavior, when executing Java programs, the JVM in Java finds and loads classes, and it is classpaths job to tell Java where to look in the file system for files defining these classes.
The Java Virtual Machine searches for classes in this order:
- Bootstrap classes - the classes that are crucial to the Java Platform
- Extension classes - packages that are in the extension directory of the JRE or JDK
- User defined packages and libraries
By default only the packages of the JDK standard API and extension packages are accessible without needing to set where to find them. The path for all used-defined packages and libraries must be set in the command-line
When and how to update (set) the Classpath
If you are trying to run a stand-alone Java Program, it can be necessary to update the classpath variable. When the program runs, Java runtime environment is working through your code. If it comes across a class name, it will look at each directory listen in the classpath variable. In case it does not find the class name, it will throw an error.
Now that we explained when to change we also have explain how to update it. Classpath can be updated same as Path variable is, just instead of Path, use Classpath. To learn more about it go to Install JDK aka Java SDK article.
In the Read file from classpath we will explain more detailed how to use classpath in Java