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.


Top Hashtags:

Advertisements

Advertisements




Advertisements