Home > Java > javaTutorial > body text

How to Load Resource Files Using getClass().getResource() in Java?

Linda Hamilton
Release: 2024-11-11 08:05:02
Original
613 people have browsed it

How to Load Resource Files Using getClass().getResource() in Java?

Loading Files Using getClass().getResource()

When attempting to load a resource file using getClass().getResource(path), it's essential to ensure that the resource is accessible through the classpath.

In Eclipse, files placed in the source folder are automatically copied to the bin directory during compilation. Therefore, your resource file, Test.properties, is accessible when launching the program from within the IDE because the bin directory is added to the classpath.

However, when running the program from the command line using javac and java commands, the bin directory is not automatically included in the classpath. You must explicitly add the bin directory to the classpath using the -classpath option.

Here's an example of how you can compile and run the program from the command line:

javac -classpath . CustomDialog.java
java -classpath . SwingDemo.CustomDialog
Copy after login

Alternatively, you can use getClass().getResourceAsStream(), which directly loads the resource as an InputStream without relying on the file system. To use this method:

InputStream inputStream = getClass().getResourceAsStream("Test.properties");
Copy after login

By specifying the resource path as "/com/foo/bar/Test.properties," you can load a file from a specific package.

The above is the detailed content of How to Load Resource Files Using getClass().getResource() in Java?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template