Java Reference
In-Depth Information
will search all of them. Useful for finding a series of configuration files and merging them,
perhaps. Or for finding out whether there is more than one resource/file of a given name on
your classpath.
Note that the resource name can be given as either a relative path or as an absolute path. As-
suming you are using Maven (see
Automating Dependencies, Compilation, Testing, and
Deployment with Apache Maven
)
, then for the absolute path, place the file relative to
src/
main/resources/
directory. For the absolute path, place the file in the same directory as your
source code. The same rules apply in an IDE assuming you have made
src/main/java
and
src/main/resources
be treated as “source folders” in your IDE configuration. The idea is that
“resource files” get copied to your classpath folder. For example, if you have two resource
files,
src/main/resources/one.txt
and
src/main/java/MyPackage/two.txt
, and your project is
configured as described, these two lines would work, if accessed from a program in
MyPack-
age
:
Class<?> c = getClass();
InputStream isOne = getResourceAsStream("/one.txt"); // note leading slash
InputStream isTwo = getResourceAsStream("two.txt"); // without leading slash
WARNING
In either case,
getResource()
and
getResourceAsStream()
will return
null
if they
don't find the resource; you should always check for
null
to guard against faulty deploy-
ment. However, if it doesn't find anything matching,
getResources()
will return an
empty
Enumeration
.
If the file path has slashes between components (as in
package/subpackage
), the name you
path into any of the
getResource
methods should have a “.” in place of the “/”.
Reading and Writing Compressed Files
Problem
You need to read or write files that have been compressed using GNU zip, or
gzip
. These
files are usually saved with the extension
.gz
.