Thursday, August 13, 2020

java.io.FileNotFoundException while using classLoader.getResource(fileName) method

Problem: 

I have a method loadFileFromClassPath(String fileName). Inside the method I am taking help of ClassLoader to get the File object and returning it.

    public static File loadFileFromClassPath(String fileName) {
        File file;
        ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
        file = new File(classLoader.getResource(fileName).getFile());
        return file;
    }

There is an another method method fileDataToString(String fileName) which is using loadFileFromClassPath(String fileName) method.
    public static String fileDataToString(String fileName) throws IOException {
        final StringBuilder sb = new StringBuilder();
        final InputStream is = loadFileFromClassPath(fileName);
        String line;
        try(BufferedReader br = new BufferedReader(new InputStreamReader(is))) {
        	while ((line = br.readLine()) != null) {
        		sb.append(line);
        	}
	}
        return sb.toString();
    }


But here classLoader.getResource(fileName) method is not working and causing java.io.FileNotFoundException.


FileNotFoundException



Solution:

To solve this problem you can use classLoader.getResourceAsStream(fileName) which returns InputStream.
    public static InputStream loadFileFromClassPath(String fileName) {
        ClassLoader loader = Thread.currentThread().getContextClassLoader();
        InputStream is=loader.getResourceAsStream(fileName);
        return is;
    }

And you just need to change some logic to read the data from InputStream to String in fileDataToString(String fileName) method as
    public static String fileDataToString(String fileName) throws IOException {
        final StringBuilder sb = new StringBuilder();
        final InputStream is = loadFileFromClassPath(fileName);
        String line;
        try(BufferedReader br = new BufferedReader(new InputStreamReader(is))) {
        	while ((line = br.readLine()) != null) {
        		sb.append(line);
        	}
	}
        return sb.toString();
    }

Thats it!
Happy Coding.






Share this

0 Comment to "java.io.FileNotFoundException while using classLoader.getResource(fileName) method"

Post a Comment