Java – Read a file from resources folder

In this tutorial, we will show you how to read a file from a resources folder or classpath, in both runtime and unit test environment. Try putting a file into the src/main/resources folder, and read the file with following code snippets :

1. getResource


	File file = new File(
		getClass().getClassLoader().getResource("database.properties").getFile()
	);

2. getResourceAsStream


	InputStream inputStream = getClass()
			.getClassLoader().getResourceAsStream("database.properties");
Note
You may interest at this getResourceAsStream in static method

1. Project Directory

Review a Maven project Structure.

project directory

2. Read file from resources folder

src/main/resources/database.properties

datasource.url=jdbc:mysql://localhost/mkyong?useSSL=false
datasource.username=root
datasource.password=password
datasource.driver-class-name=com.mysql.jdbc.Driver

Read database.properties file and print out the content.

Application.java

package com.mkyong;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.net.URL;

public class Application {

    public static void main(String[] args) throws IOException {

        Application main = new Application();
        File file = main.getFileFromResources("database.properties");

        printFile(file);
    }

    // get file from classpath, resources folder
    private File getFileFromResources(String fileName) {

        ClassLoader classLoader = getClass().getClassLoader();

        URL resource = classLoader.getResource(fileName);
        if (resource == null) {
            throw new IllegalArgumentException("file is not found!");
        } else {
            return new File(resource.getFile());
        }

    }

    private static void printFile(File file) throws IOException {

        if (file == null) return;

        try (FileReader reader = new FileReader(file);
             BufferedReader br = new BufferedReader(reader)) {

            String line;
            while ((line = br.readLine()) != null) {
                System.out.println(line);
            }
        }
    }

}

Output


datasource.url=jdbc:mysql://localhost/mkyong?useSSL=false
datasource.username=root
datasource.password=password
datasource.driver-class-name=com.mysql.jdbc.Driver

3. Unit Test

src/test/resources/xml/data.xml

<test>
    <case id='1'>
        <param>100</param>
        <expected>mkyong</expected>
    </case>
    <case id='2'>
        <param>99</param>
        <expected>mkyong</expected>
    </case>
</test>

Read data.xml and print out the content.

ApplicationTest.java

package com.mkyong;

import org.apache.commons.io.IOUtils;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;

import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;

public class ApplicationTest {

    @DisplayName("Test loading XML")
    @Test
    void loadXMLTest() {

        ClassLoader classLoader = getClass().getClassLoader();

        try (InputStream inputStream = classLoader.getResourceAsStream("xml/data.xml")) {

            String result = IOUtils.toString(inputStream, StandardCharsets.UTF_8);
            System.out.println(result);

        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

Output


<test>
    <case id='1'>
        <param>100</param>
        <expected>mkyong</expected>
    </case>
    <case id='2'>
        <param>99</param>
        <expected>mkyong</expected>
    </case>
</test>
pom.xml

	<dependencies>
        <dependency>
            <groupId>commons-io</groupId>
            <artifactId>commons-io</artifactId>
            <version>2.6</version>
        </dependency>

        <dependency>
            <groupId>org.junit.jupiter</groupId>
            <artifactId>junit-jupiter</artifactId>
            <version>5.4.2</version>
            <scope>test</scope>
        </dependency>

    </dependencies>

Download Source Code

References

About the Author

author image
mkyong
Founder of Mkyong.com, love Java and open source stuff. Follow him on Twitter, or befriend him on Facebook or Google Plus. If you like my tutorials, consider make a donation to these charities.

Comments

avatar
26 Comment threads
10 Thread replies
1 Followers
 
Most reacted comment
Hottest comment thread
35 Comment authors
ANKUROvidiurobben09nameMubeen Recent comment authors
newest oldest most voted
alikemal ocalan
Guest
alikemal ocalan

Hi mkyong.This work fine ide but not work jar?
Can you help we ?

name
Guest
name

ClassLoader classLoader = ClassLoader.getSystemClassLoader();
InputStream inputStream = classLoader.getResourceAsStream(“fileName”);
StringWriter writer = new StringWriter();
IOUtils.copy(inputStream, writer);
query = writer.toString();

robben09
Guest
robben09

^ Thanks a lot man!

Luke
Guest
Luke

What if you get NullPointer when retrieving the resource? Resource is in src/main/resources.

Jack Nolddor
Guest
Jack Nolddor

How about reading al files under a resources directory like this?

src/main/resources
+ file1.txt
+ file2.txt

+ file9.txt

Grzegorz Solecki
Guest
Grzegorz Solecki

There is also one that I like the most:
File file = ResourceUtils.getFile(“classpath:file/test.txt”)
String txt= FileUtils.readFileToString(file);

ResourceUtils are in spring and FileUtils are in commons io.

mkyong
Guest
mkyong

Thanks for sharing this – ResourceUtils

Khue Nguyen
Guest
Khue Nguyen

OMG, many thanks for this ^^

Karl Huebner
Guest
Karl Huebner

new File(classLoader.getResource(fileName).getFile());This won’t work with files if they have whitespaces or special characters (e.g. #) in their paths. Rather use

new File(classLoader.getResource(fileName).toURI());

Brandon Dudek
Guest
Brandon Dudek

Thank You!

Mohammed Salman
Guest
Mohammed Salman

Thanks to MyKong and you I got it working!

ANKUR
Guest
ANKUR

toURI() does not work in jar and gives a error: URI is not hierarchical

Gavriel
Guest
Gavriel

Why do you need the line:
scanner.close();
in the classic example, if you already have try-with-resources:
try (Scanner scanner = new Scanner(file)) {..}

Mubeen
Guest
Mubeen

How to read a file not in Resources folder

daniel
Guest
daniel

Excellent!!

Moreno Garcia
Guest
Moreno Garcia

If I have this code
InputStream in = this.getClass().getClassLoader().getResourceAsStream(somefile.txt);

And my application is deployed on tomcat8. Where should I put somefile.txt so it can be found by the app?

Mohammed Salman
Guest
Mohammed Salman

Thanks!

Dani
Guest
Dani

Obrigado, gracias

Leandro Temperoni
Guest
Leandro Temperoni

Thank you! This was reeeeeeeally helpful!

Pedro Rios
Guest
Pedro Rios

Great!

Krishna
Guest
Krishna

I have put lot of efforts but finally i found solution from here great…………..

Andrei Bardezi
Guest
Andrei Bardezi

Is there a way of writing to the same file, once the application is ran?

Jane
Guest
Jane

I tried this but it looks in the target foler and not the resource folder.

Ovidiu
Guest
Ovidiu

same here.I used the first example and I get FileNotFoundException: …testClassLoader\target\classes\file\test.txt (The system cannot find the path specified)

Adhi
Guest
Adhi

did case is the same as the file jasper

Jan Khonski
Guest
Jan Khonski

Why do you use forward slash as a file separator. Why not File.separator, which fails on Windows. And why does File.separator fail on Windows? What should I use (but not hardcoded)?

Carol
Guest
Carol

Thanks for sharing

Pavel
Guest
Pavel

@mkyong:disqus Thank you for article! But I have a question. How to read file test.xml in Hello class (instead of TestHello)?

AntuanSfot
Guest
AntuanSfot

AntuanSoft:

To use in a static context you have to use:

ClassLoader classLoader = ClassLoader.getSystemClassLoader();

Anderson Gomes
Guest
Anderson Gomes

ClassLoader classLoader = Hello.class.getClassLoader() also works.

Nirupama
Guest
Nirupama

I would like to know how to know how to extract files which are in a folder which itself is in another folder.

Neeraj Lal
Guest
Neeraj Lal

how do you write files to resources folder (on eclipse env)?

nosperov
Guest
nosperov

Hi,
It work :)!
I have a question: How do to return an array with 4 file lines, chosen randomly from file?

Anirban Kundu
Guest
Anirban Kundu

Thanks . Worked like a charm !

Antony
Guest
Antony

try (Scanner scanner = new Scanner(file)) {

scanner.close()

Why do you close scanner explicitly? I thought ‘try with resources’ can do it by itself.

mkyong
Guest
mkyong

ya, with JDK 7, it should close automatically, It’s hard to change my old days practice :)