I am trying to read a text file which is set in CLASSPATH system variable. Not a user variable.
I am trying to get input stream to the file as below:
Place the directory of file (D:\myDir
)in CLASSPATH and try below:
InputStream in = this.getClass().getClassLoader().getResourceAsStream("SomeTextFile.txt");
InputStream in = this.getClass().getClassLoader().getResourceAsStream("/SomeTextFile.txt");
InputStream in = this.getClass().getClassLoader().getResourceAsStream("//SomeTextFile.txt");
Place full path of file (D:\myDir\SomeTextFile.txt
)in CLASSPATH and try the same above 3 lines of code.
But unfortunately NONE of them are working and I am always getting null
into my InputStream in
.
Don't use getClassLoader() method and use the "/" before the file name. "/" is very important
you have to put your 'system variable' on the java classpath.
To read the contents of a file into a String from the
classpath
, you can use this:Note:
IOUtils
is part ofCommons IO
.Call it like this:
Scenario:
1)
client-service-1.0-SNAPSHOT.jar
has dependencyread-classpath-resource-1.0-SNAPSHOT.jar
2) we want to read content of class path resources (
sample.txt
) ofread-classpath-resource-1.0-SNAPSHOT.jar
throughclient-service-1.0-SNAPSHOT.jar
.3)
read-classpath-resource-1.0-SNAPSHOT.jar
hassrc/main/resources/sample.txt
1.
pom.xml
ofread-classpath-resource-1.0-SNAPSHOT.jar
2.
ClassPathResourceReadTest.java
class inread-classpath-resource-1.0-SNAPSHOT.jar
that loads the class path resources file content.3.
pom.xml
ofclient-service-1.0-SNAPSHOT.jar
4.
AccessClassPathResource.java
instantiateClassPathResourceReadTest.java
class where, it is going to loadsample.txt
and prints its content also.5.Run Executable jar as follows:
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.
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.
With the directory on the classpath, from a class loaded by the same classloader, you should be able to use either of:
If those aren't working, that suggests something else is wrong.
So for example, take this code:
And this directory structure:
And then (using the Unix path separator as I'm on a Linux box):
Results: