Главная » Ошибки » Java Read File from Resources Folder

Java Read File from Resources Folder

1. Packaging a File into resources Folder

The resources folder belongs to the maven project structure where we place the configuration and data files related to the application. The location of the folder is “src/main/resources“.

  • When packaging the application as jar file, the file present in the resources folder are copied in the root target/classes folder.
    In this case, the file location is inside a zipped archive like jar-filename.jar/!filename.txt. We should directly read this file as InputStream.
  • When packaging the application as war file, the file present in the resources folder are copied in the root target/app-name folder.
    After the deployment, war files are extracted in a server work directory. So, in this case, we are reading the file outside a zipped archive so we can refer to the file using a relative path. We can refer to this file using File instance and can use any suitable method to read the file content.

In the given examples, we are reading two files present in the resources folder. The first file demo.txt is at the root of resources folder. The second file data/demo.txt folder is inside a nested folder data in the resources folder.


The file locations in the resources folder

3. Source Code vs Compiled Code

When we build a JAR, the resources get placed into the root directory of the packaged artifacts.

In our example, we see the source code setup has input.txt in src/main/resources in our source code directory.

In the corresponding JAR structure, however, we see:

META-INF/MANIFEST.MF
META-INF/
com/
com/baeldung/
com/baeldung/resource/
META-INF/maven/
META-INF/maven/com.baeldung/
META-INF/maven/com.baeldung/core-java-io-files/
input.txt
com/baeldung/resource/MyResourceLoader.class
META-INF/maven/com.baeldung/core-java-io-files/pom.xml
META-INF/maven/com.baeldung/core-java-io-files/pom.properties

Here, input.txt is at the root directory of the JAR. So when the code executes, we’ll see the FileNotFoundException.

Even if we changed the path to /input.txt the original code could not load this file as resources are not usually addressable as files on disk. The resource files are packaged inside the JAR and so we need a different way of accessing them.

2. Resources Packaged as .jar File

2.1. ClassLoader.getResourceAsStream()

Use the getResourceAsStream() method to get the InputStream when reading a file from inside a jar file. Always use this method on the ClassLoader instance.

private InputStream getFileAsIOStream(final String fileName)
{
InputStream ioStream = this.getClass()
.getClassLoader()
.getResourceAsStream(fileName);

if (ioStream == null) {
throw new IllegalArgumentException(fileName + » is not found»);
}
return ioStream;
}

2.2. Complete Example

Once we have the InputStream reference, we can use it to read the file content or pass it to any resource handler class.

package com.howtodoinjava.io;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

public class ReadFileFromResourcesUsingGetResourceAsStream
{
public static void main(final String[] args) throws IOException
{
//Creating instance to avoid static member methods
ReadFileFromResourcesUsingGetResourceAsStream instance
= new ReadFileFromResourcesUsingGetResourceAsStream();

InputStream is = instance.getFileAsIOStream(«demo.txt»);
instance.printFileContent(is);

is = instance.getFileAsIOStream(«data/demo.txt»);
instance.printFileContent(is);
}

private InputStream getFileAsIOStream(final String fileName)
{
InputStream ioStream = this.getClass()
.getClassLoader()
.getResourceAsStream(fileName);

if (ioStream == null) {
throw new IllegalArgumentException(fileName + » is not found»);
}
return ioStream;
}

private void printFileContent(InputStream is) throws IOException
{
try (InputStreamReader isr = new InputStreamReader(is);
BufferedReader br = new BufferedReader(isr);)
{
String line;
while ((line = br.readLine()) != null) {
System.out.println(line);
}
is.close();
}
}
}

2.3. How to test the code

To test the above code, package the application as jar file using mvn clean package command. Also, provide the mainClass attribute to maven-jar-plugin and set its value to the class which has main() method and the test code.

org.apache.maven.plugins
maven-jar-plugin
3.2.0



com.howtodoinjava.io.
ReadFileFromResourcesUsingGetResourceAsStream



Now, run the main() method from the console.

mvn clean package
java -jar targetapp-build-name.jar

Add your solution here

 B  I  U  S smallBIGcodePlain TextASMASPASP.NETBASICBATC#C++COBOLCoffeeScriptCSSDartdbaseF#FORTRANHTMLJavaJavascriptKotlinLuaMIDLMSILObjectiveCPascalPERLPHPPowerShellPythonRazorRubyScalaShellSLNSQLSwiftT4TerminalTypeScriptVBVBScriptXMLvar <  >  & link[^]encodeuntabcaseindentoutdent

<текстареа name="ctl00$ctl00$MC$AMC$PostEntryObj$Content$MessageText" id="ctl00_ctl00_MC_AMC_PostEntryObj_Content_MessageText" class="resizable text-editor" style="width:100%;height:250px;">

OKPaste as

Strip HTML
Encode HTML
Paste as-is
Code block
Quoted Text
Best guess

To display as

The content must be between 30 and 50000 characters.Treat my content as plain text, not as HTML

5. Conclusion

In this quick article, we implemented loading files as classpath resources, to allow our code to work consistently regardless of how it was packaged.

As always, the example code is available over on GitHub.

Java bottom

Get started with Spring 5 and Spring Boot 2, through the Learn Spring course:

>> CHECK OUT THE COURSE Generic footer banner

Courses

  • All Courses
  • All Bulk Courses
  • All Bulk Team Courses
  • The Courses Platform

Using DataInputStream

Next, we will cover an example of using DataInputStream to read data from a file in src/main/resources directory. The DataInputStream is useful for reading primitive java data types from a file.

try (
InputStream inputStream = this.getClass().getResourceAsStream(«/file.txt»);
DataInputStream dataInputStream = new DataInputStream(inputStream);
) {
int numBytesRead;
if ((numBytesRead = dataInputStream.available()) > 0) {
byte[] bucket = newbyte[numBytesRead];
dataInputStream.read(bucket);
System.out.println(new String(bucket));
}
}Code language:Java(java)

3. Resources Packaged as .war File

3.1. ClassLoader.getResource()

Use the getResource() method to get the File instance when reading a file from inside a war file. I suggest using this method on the ClassLoader instance.

private File getResourceFile(final String fileName)
{
URL url = this.getClass()
.getClassLoader()
.getResource(fileName);

if(url == null) {
throw new IllegalArgumentException(fileName + » is not found 1″);
}

File file = new File(url.getFile());

return file;
}

3.2. Complete Example

Now use the File reference to read the file content.

package com.howtodoinjava.io;

import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URL;
import java.nio.file.Files;

public class ReadFileFromResourcesUsingGetResource {
public static void main(final String[] args) throws IOException
{
//Creating instance to avoid static member methods
ReadFileFromResourcesUsingGetResource instance
= new ReadFileFromResourcesUsingGetResource();

File file = instance.getResourceFile(«demo.txt»);
instance.printFileContent(file);

file = instance.getResourceFile(«data/demo.txt»);
instance.printFileContent(file);
}

private File getResourceFile(final String fileName)
{
URL url = this.getClass()
.getClassLoader()
.getResource(fileName);

if(url == null) {
throw new IllegalArgumentException(fileName + » is not found 1″);
}

File file = new File(url.getFile());

return file;
}

private void printFileContent(File file) throws IOException
{
String content = new String(Files.readAllBytes(file.toPath()));
System.out.println(content);
}

private void printFileContent(InputStream is) throws IOException
{
try (InputStreamReader isr = new InputStreamReader(is);
BufferedReader br = new BufferedReader(isr);)
{
String line;
while ((line = br.readLine()) != null) {
System.out.println(line);
}
is.close();
}
}
}

3.3. How to test the code

To test the above code, package the application as a war file using mvn clean package command. Use the maven-resources-plugin plugin to copy the files from the resources folder to the root of the war file archive.

org.apache.maven.plugins
maven-war-plugin
3.2.0

false

maven-resources-plugin
2.4.3


copy-resources

process-resources

copy-resources


true
${project.build.directory}
/${project.artifactId}-${project.version}/



${project.basedir}/src/main/resources




Now, run the main method from the console. Do not forget to add the classes to the classpath.

mvn clean package
java -classpath «classes/.» com.howtodoinjava.io.ReadFileFromResourcesUsingGetResource

1. Overview

In this tutorial, we’ll explore an issue that can come up when reading resource files in a Java application: At runtime, the resource folder is seldom in the same location on disk as it is in our source code.

Let’s see how Java allows us to access resource files after our code has been packaged.

Preview 0

Existing Members

Sign in to your account

Using Java getResourceAsStream()

This is an example of using getResourceAsStream method to read a file from src/main/resources directory.

try (
InputStream inputStream = this.getClass().getResourceAsStream(«/file.txt»);
InputStreamReader inputStreamReader = new InputStreamReader(inputStream);
BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
Stream lines = bufferedReader.lines();
) {
lines.forEach(System.out::println);
}Code language:Java(java)

First, we are using the getResourceAsStream method to create an instance of InputStream. Next, we create an instance of InputStreamReader for the input stream. Then, we wrap the input stream reader into a BufferedReader instance.

The lines method on the BufferedReader class returns a Stream of Strings which are lazily read from the file. We are then printing each line from the file on the console.

Note that, in Java File IO we need explicitly close all of the streams and readers that we create. Also, the Java 8 Streams which are generated from File IO resources need to be closed. To do that, we are using a try-with-resources block to instantiate them.

Alternatively, we can use getResourceAsStream on the class loader.

InputStream inputStream = this.getClass()
.getClassLoader()
.getResourceAsStream(«file.txt»);Code language:Java(java)

The difference between the two is that when we use getResourceAsStream on the class the path is relative to current directory. Thus, we added a slash (/) to the path. On the other hand getResourceAsStream on the class loader instance takes absolute path. Which is why we have not added the slash (/).

2. Reading Files

Let’s say our application reads a file during startup:

try (FileReader fileReader = new FileReader(«src/main/resources/input.txt»);
BufferedReader reader = new BufferedReader(fileReader)) {
String contents = reader.lines()
.collect(Collectors.joining(System.lineSeparator()));
}

If we run the above code in an IDE, the file loads without an error. This is because our IDE uses our project directory as its current working directory and the src/main/resources directory is right there for the application to read.

Now let’s say we use the Maven JAR plugin to package our code as a JAR.

When we run it at the command line:

java -jar core-java-io2.jar

We’ll see the following error:

Exception in thread «main» java.io.FileNotFoundException:
src/main/resources/input.txt (No such file or directory)
at java.io.FileInputStream.open0(Native Method)
at java.io.FileInputStream.open(FileInputStream.java:195)
at java.io.FileInputStream.(FileInputStream.java:138)
at java.io.FileInputStream.(FileInputStream.java:93)
at java.io.FileReader.(FileReader.java:58)
at com.baeldung.resource.MyResourceLoader.loadResourceWithReader(MyResourceLoader.java:14)
at com.baeldung.resource.MyResourceLoader.main(MyResourceLoader.java:37)

Источники

  • https://howtodoinjava.com/java/io/read-file-from-resources-folder/
  • https://www.baeldung.com/java-classpath-resource-cannot-be-opened
  • https://www.codeproject.com/Questions/376141/Parser-error-Could-not-load-type
  • https://www.amitph.com/java-read-file-from-resources-folder/
[свернуть]
Решите Вашу проблему!


×
Adblock
detector