0

In the sample program below I am invoking the getResource(...).getFile() method twice, in a Windows environment.

In both cases the URI passed to the getResource method is a local file name, and the file exists. The difference is that in the first case there is no whitespace in the name, but in the second case there is a whitespace in the name. Things work well in the first case but in the second case I get the java.io.FileNotFoundException.

Sample code follows:

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;

public class GetResourceExpt {
    static String fileUri1 = "./subfolder/data.txt";
    static String fileUri2 = "./sub folder/data.txt";

    public static void main(String[] args) throws IOException {
        String fileName1 = GetResourceExpt.class.getResource(fileUri1).getFile();
        BufferedReader br1 = new BufferedReader(new FileReader(fileName1));
        System.out.println("Buffered Reader 1 instantiated!");
        br1.close();

        String fileName2 = GetResourceExpt.class.getResource(fileUri2).getFile();
        BufferedReader br2 = new BufferedReader(new FileReader(fileName2));
        System.out.println("Buffered Reader 2 instantiated!");
        br2.close();
    }
}
Michiel Leegwater
  • 1,172
  • 4
  • 11
  • 27
Sandeep
  • 1,245
  • 1
  • 13
  • 33
  • 2
    Do NOT use file IO to read classpath resources. Use getResourceAsStream(): that gives you an InputStream that you can wrap in an InputStreamReader. Classpath resources are NOT files. – JB Nizet Oct 13 '19 at 08:53
  • Using getResourceAsStream appears to be a good suggestion. However, could you suggest what to do if you want to locate a resource and then open it for writing? – Sandeep Oct 13 '19 at 09:02
  • 2
    Classpath resources are read-only. If you want to write, use an actual file, not a classpath resource. – JB Nizet Oct 13 '19 at 09:05
  • This may help you https://stackoverflow.com/questions/3263560/sysloader-getresource-problem-in-java?answertab=active#tab-top – Adnan Temur Oct 13 '19 at 18:16

0 Answers0