How to 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.class
txt
SomeTextFile.txt
And then (using the Unix path separator as I'm on a Linux box):
java -classpath code:txt dummy.Test
Results:
true
true
How do I load a file from resource folder?
Try the next:
ClassLoader classloader = Thread.currentThread().getContextClassLoader();
InputStream is = classloader.getResourceAsStream("test.csv");
If the above doesn't work, various projects have been added the following class: ClassLoaderUtil
1 (code here).2
Here are some examples of how that class is used:
src\main\java\com\company\test\YourCallingClass.java
src\main\java\com\opensymphony\xwork2\util\ClassLoaderUtil.java
src\main\resources\test.csv
// java.net.URL
URL url = ClassLoaderUtil.getResource("test.csv", YourCallingClass.class);
Path path = Paths.get(url.toURI());
List<String> lines = Files.readAllLines(path, StandardCharsets.UTF_8);
// java.io.InputStream
InputStream inputStream = ClassLoaderUtil.getResourceAsStream("test.csv", YourCallingClass.class);
InputStreamReader streamReader = new InputStreamReader(inputStream, StandardCharsets.UTF_8);
BufferedReader reader = new BufferedReader(streamReader);
for (String line; (line = reader.readLine()) != null;) {
// Process line
}
Notes
- See it in The Wayback Machine.
- Also in GitHub.
Reading a resource file from within jar
Rather than trying to address the resource as a File just ask the ClassLoader to return an InputStream for the resource instead via getResourceAsStream:
try (InputStream in = getClass().getResourceAsStream("/file.txt");
BufferedReader reader = new BufferedReader(new InputStreamReader(in))) {
// Use resource
}
As long as the file.txt
resource is available on the classpath then this approach will work the same way regardless of whether the file.txt
resource is in a classes/
directory or inside a jar
.
The URI is not hierarchical
occurs because the URI for a resource within a jar file is going to look something like this: file:/example.jar!/file.txt
. You cannot read the entries within a jar
(a zip
file) like it was a plain old File.
This is explained well by the answers to:
- How do I read a resource file from a Java jar file?
- Java Jar file: use resource errors: URI is not hierarchical
How to read file from relative path in Java project? java.io.File cannot find the path specified
If it's already in the classpath, then just obtain it from the classpath instead of from the disk file system. Don't fiddle with relative paths in java.io.File
. They are dependent on the current working directory over which you have totally no control from inside the Java code.
Assuming that ListStopWords.txt
is in the same package as your FileLoader
class, then do:
URL url = getClass().getResource("ListStopWords.txt");
File file = new File(url.getPath());
Or if all you're ultimately after is actually an InputStream
of it:
InputStream input = getClass().getResourceAsStream("ListStopWords.txt");
This is certainly preferred over creating a new File()
because the url
may not necessarily represent a disk file system path, but it could also represent virtual file system path (which may happen when the JAR is expanded into memory instead of into a temp folder on disk file system) or even a network path which are both not per definition digestable by File
constructor.
If the file is -as the package name hints- is actually a fullworthy properties file (containing key=value
lines) with just the "wrong" extension, then you could feed the InputStream
immediately to the load()
method.
Properties properties = new Properties();
properties.load(getClass().getResourceAsStream("ListStopWords.txt"));
Note: when you're trying to access it from inside static
context, then use FileLoader.class
(or whatever YourClass.class
) instead of getClass()
in above examples.
How to reference an included file in OSGi bundle when performing java.io.File or FileInputStream
The Bundle interface has a getEntry(java.lang.String path)
method which return an Url and is documented as:
Returns a URL to the entry at the specified path in this bundle. This bundle's class loader is not used to search for the entry. Only the contents of this bundle are searched for the entry.
The specified path is always relative to the root of this bundle and may begin with "/". A path value of "/" indicates the root of this bundle.
Related Topics
How to Deserialize the Object, If It Was Moved to Another Package or Renamed
Understanding Jsf as a MVC Framework
Does Java Have Buffer Overflows
"File Not Found" When Running New Libgdx Project
Creating Classes Dynamically with Java
How to Convert Pojo to JSON and Vice Versa
How to Make Line Animation Smoother
How to Manually Set an Authenticated User in Spring Security/Springmvc
How to Write an Arraylist of Strings into a Text File
Is Memory Leak? Why Java.Lang.Ref.Finalizer Eat So Much Memory
How to Sort Arraylist<Long> in Decreasing Order
Improvednamingstrategy No Longer Working in Hibernate 5
How to Encode Uri Parameter Values
Java's Bigdecimal.Power(Bigdecimal Exponent): Is There a Java Library That Does It