How to really read text file from classpath in Java How to really read text file from classpath in Java java java

How to really read text file from classpath in Java


With the directory on the classpath, from a class loaded by the same classloader, you should be able to use either of:

// From ClassLoader, all paths are "absolute" already - there's no context// from which they could be relative. Therefore you don't need a leading slash.InputStream in = this.getClass().getClassLoader()                                .getResourceAsStream("SomeTextFile.txt");// From Class, the path is relative to the package of the class unless// you include a leading slash, so if you don't want to use the current// package, include a slash like this:InputStream in = this.getClass().getResourceAsStream("/SomeTextFile.txt");

If those aren't working, that suggests something else is wrong.

So for example, take this code:

package dummy;import java.io.*;public class Test{    public static void main(String[] args)    {        InputStream stream = Test.class.getResourceAsStream("/SomeTextFile.txt");        System.out.println(stream != null);        stream = Test.class.getClassLoader().getResourceAsStream("SomeTextFile.txt");        System.out.println(stream != null);    }}

And this directory structure:

code    dummy          Test.classtxt    SomeTextFile.txt

And then (using the Unix path separator as I'm on a Linux box):

java -classpath code:txt dummy.Test

Results:

truetrue


When using the Spring Framework (either as a collection of utilities or container - you do not need to use the latter functionality) you can easily use the Resource abstraction.

Resource resource = new ClassPathResource("com/example/Foo.class");

Through the Resource interface you can access the resource as InputStream, URL, URI or File. Changing the resource type to e.g. a file system resource is a simple matter of changing the instance.


This is how I read all lines of a text file on my classpath, using Java 7 NIO:

...import java.nio.charset.Charset;import java.nio.file.Files;import java.nio.file.Paths;...Files.readAllLines(    Paths.get(this.getClass().getResource("res.txt").toURI()), Charset.defaultCharset());

NB this is an example of how it can be done. You'll have to make improvements as necessary. This example will only work if the file is actually present on your classpath, otherwise a NullPointerException will be thrown when getResource() returns null and .toURI() is invoked on it.

Also, since Java 7, one convenient way of specifying character sets is to use the constants defined in java.nio.charset.StandardCharsets(these are, according to their javadocs, "guaranteed to be available on every implementation of the Java platform.").

Hence, if you know the encoding of the file to be UTF-8, then specify explicitly the charset StandardCharsets.UTF_8