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.
How to read files from a resources folder in java?
If you have shader.glsl
file in your resource folder. I.e. when you build jar file it will copy to the jar root. Then you can read it as stream:
ClassLoader classloader = Thread.currentThread().getContextClassLoader();
InputStream in = classloader.getResourceAsStream("/shader.glsl");
How to load file from resources directory in Java
Following code expects that the resource, you are trying to access, exists in your class path.
getClassLoader().getResourceAsStream(resourceName))
Assuming that your file exists in src/resources: You may add src/resources/ in your classpath. I don't know which IDE are you using but here are some ways to add a directory in the classpath:
- Intelli J : how to add directory to classpath in an application run profile in intellij idea?
- Eclipse : How do I add a directory to the eclipse classpath?
- At run time : Can a directory be added to the class path at runtime?
- At command line : http://javarevisited.blogspot.com/2012/10/5-ways-to-add-multiple-jar-to-classpath-java.html
How to Properly Get a File from resources Folder
Test.class.getClassLoader();
obtains a reference to the ClassLoader
class from the Class
' method public ClassLoader getClassLoader()
- see private final ClassLoader classLoader
below.
Since you are accessing the ClassLoader
class from an object of that class, you're not accessing it in a static way.
From Class.java
, Java SE 1.7:
@CallerSensitive
public ClassLoader getClassLoader() {
ClassLoader cl = getClassLoader0();
if (cl == null)
return null;
SecurityManager sm = System.getSecurityManager();
if (sm != null) {
ClassLoader.checkClassLoaderPermission(cl, Reflection.getCallerClass());
}
return cl;
}
// Package-private to allow ClassLoader access
ClassLoader getClassLoader0() { return classLoader; }
// Initialized in JVM not by private constructor
// This field is filtered from reflection access, i.e. getDeclaredField
// will throw NoSuchFieldException
private final ClassLoader classLoader;
In order to access the method in a static way, it has to be called from the class which declares it as static if you want to get rid of the warning:
ClassLoader.getSystemResource("test.html").getFile()
To avoid the NPE the test.html
file should be under your source folder.
To respond to your comment, using a method which returns other than a URL
solves your problem - see Reading a resource file from within jar.
public class Test {
public static void main(String[] args) {
StringBuilder contentBuilder = new StringBuilder();
InputStream is = Test.class.getResourceAsStream("/test.html");
try {
String sCurrentLine;
BufferedReader buffer = new BufferedReader(new InputStreamReader(is));
while ((sCurrentLine = buffer.readLine())!=null)
contentBuilder.append(sCurrentLine);
buffer.close();
} catch (Exception e) {
e.printStackTrace();
System.exit(-1);
}
System.out.println("content=" + contentBuilder.toString());
}
}
Can't Access File in Resources Folder
Read the resource contents as a Stream (instead of the URL or file path)
public static void main(String[] args) throws IOException {
InputStream in = Application.class.getClassLoader().getResourceAsStream("bern.png");
BufferedImage testImage = ImageIO.read(in);
ImageIcon icon = new ImageIcon(testImage);
}
Related Topics
What's the Difference Between Next() and Nextline() Methods from Scanner Class
How to Read a Single Char from the Console in Java (As the User Types It)
How to Use the Tostring Method in Java
How to Get the Insert Id in Jdbc
Create Instance of Generic Type in Java
Converting Json Data to Java Object
How Are Anonymous Inner Classes Used in Java
How to Solve "Java.Lang.Noclassdeffounderror"
How to Read a Large Text File Line by Line Using Java
Java: Splitting a Comma-Separated String But Ignoring Commas in Quotes
How to Read Xml Using Xpath in Java
Why Is Processing a Sorted Array Faster Than Processing an Unsorted Array
Run Java Class File from PHP Script on a Website
Can't Start Eclipse - Java Was Started But Returned Exit Code=13
How to "Scan" a Website (Or Page) For Info, and Bring It into My Program