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. If you like my tutorials, consider make a donation to these charities.

Comments

avatar
29 Comment threads
11 Thread replies
0 Followers
 
Most reacted comment
Hottest comment thread
39 Comment authors
ROGER DELOY PACKJose Requeijo FigueirasKaty xinh depAndreas MüllerANKUR Recent comment authors
newest oldest most voted
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

alikemal ocalan
Guest
alikemal ocalan

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

Luke
Guest
Luke

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

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.

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());

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!!

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.

Anirban Kundu
Guest
Anirban Kundu

Thanks . Worked like a charm !

nosperov
Guest
nosperov

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

Neeraj Lal
Guest
Neeraj Lal

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

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.

AntuanSfot
Guest
AntuanSfot

AntuanSoft:

To use in a static context you have to use:

ClassLoader classLoader = ClassLoader.getSystemClassLoader();

Carol
Guest
Carol

Thanks for sharing

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)?

Adhi
Guest
Adhi

did case is the same as the file jasper

Jane
Guest
Jane

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

Andrei Bardezi
Guest
Andrei Bardezi

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

Krishna
Guest
Krishna

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

Pedro Rios
Guest
Pedro Rios

Great!

Leandro Temperoni
Guest
Leandro Temperoni

Thank you! This was reeeeeeeally helpful!

Dani
Guest
Dani

Obrigado, gracias

Mohammed Salman
Guest
Mohammed Salman

Thanks!

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?

Andreas Müller
Guest
Andreas Müller

Many thanks, you save me from a major headache which was plaguing me.

Jose Requeijo Figueiras
Guest
Jose Requeijo Figueiras

Hello and thanks in advance. What about of reading not txt files? I.e. an .odf file?

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)?

Katy xinh dep
Guest
Katy xinh dep

InputStream fis = getClass().getClassLoader().getResourceAsStream(“fileName.json”);
JSONParser jsonParser = new JSONParser();
JSONObject jsonObject = (JSONObject) jsonParser.parse(
new InputStreamReader(fis, “UTF-8”));