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
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");
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!