Read file from resources folder in Java project code


In order to read a file from the resources folder make use of the getResourceAsStream method from the ClassLoader class,

Java project resources folder
Java project resources folder
Example:
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;

/**
 *
 * Read file from the resources folder
 * using Java code.
 *
 */
public class Main {

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

        String fileName="resource.properties";
        String line;
        ClassLoader classLoader = Main.class.getClassLoader();
        InputStream inputStream = classLoader.getResourceAsStream(fileName);

        if(inputStream == null) {
            throw new IOException(fileName + " file not found!");
        }

        InputStreamReader streamReader = new InputStreamReader(inputStream, StandardCharsets.UTF_8);
        BufferedReader bufferedReader = new BufferedReader(streamReader);

        while ((line = bufferedReader.readLine()) != null) {
            String[] element = line.split("\\=");
            System.out.println("Key: " + element[0]+" , Value: " +element[1]);
        }
    }
}
Output:
Key: name , Value: code2care
Key: username , Value: admin
Key: password , Value: 123456

You will receive a IOException if the file is not found.

Advertisements
Try Out Code2care Dev Tools:

Advertisements

Advertisements
Code2care is an initiative to publish and share varied knowledge in programming and technical areas gathered during day-to-day learnings and development activities.

Students and software developers can leverage this portal to find solutions to their various queries without re-inventing the wheel by referring to our easy to understand posts. Technical posts might include learnings, tutorials, trouble-shooting steps, video tutorials, code snippets, how-to, blogs, articles, etc.

🎉 We are celebrating the 10th years of Code2care! Thank you for all your support!

We strongly support Gender Equality & Diversity.