Not all uses of resources must make use of ResourceBundle. A "bundled" resource is, according to a larger definition, one that is bundled inside the JAR.
Just as the properties file, other types of bundled resources can't be placed willy-nilly, but must be put into a predictable place in the JAR. Where something in your IDE will end up and what path you open it on is the crux of the problem.
Inside this codeIn terms of beginning Java samples you have:
|
In-JAR resources...
Here's how this really works. Some of what's said below is inaccurate conjecture, but it works enough and I'll come back to correct when I discover otherwise.
Assume a file, simple-resource.txt on the project workspace path project/src/main/resources/simple-resource.txt.
Getting any class, but why not this one even though it's just a test class, the important bit is that it the filesystem path will be relative to the package of our class, then calling getResourceAsStream() with the filename will try to locate the file from our classpath on the package path, hence project/com/etretatlogiciels/bundles/simple-resource.txt.
However, prepending a starting slash ('/') on our filename makes it an absolute path and the classpath will be searched. Once of the subdirectories in our classpath is resources, which is the usual place to put local-to-JAR files.
The Eclipse non-Maven version of resources is simply under the src directory.
To get the resource into the JAR, because it will not necessarily show up there, ensure that the resources subdirectory is included. In ant, this is:
<copy todir="${classes.dir}/resources"> <fileset dir="${src.dir}/resources"> <include name="*.txt" /> </fileset> </copy>
Or something like that. What makes it show up in the IDE you're using to play around with this page is the IDE itself pretending to know what you want, because you put it there, and to create a virtual JAR accordingly.
package com.etretatlogiciels.bundles; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.util.Locale; import org.junit.Test; public class AppResourcesTest { @Test public void testSimpleResource() throws IOException { InputStream is = getClass().getResourceAsStream( "/simple-resource.txt" ); BufferedReader reader = new BufferedReader( new InputStreamReader( is ) ); String line; while( ( line = reader.readLine() ) != null ) System.out.println( line ); } } // vim: set tabstop=2 shiftwidth=2 noexpandtab:
Here's the output from the test above. What was in simple-resource.txt? Exactly what you see here.
This is a test of the Emergency Broadcast System. This is only a test. Now is the time for all good men to come to the aid of your country by joining the United States Navy. The quick brown fox jumped over the lazy dog's back and made a clean get-away. Round the rugged rocks the rascal ran.