Where to put resources and access it in Java Project (in IntelliJ)? How to read from it then?

50 Views Asked by At

I have text file, which I want to read from, but I don`t really know how to navigate from the class path to the path where the file is.

This is my project structure: Project structure photo(Intellij)

public class Main {
    public static void main(String[] args) {
        URL fileURL = Main.class.getResource("resources/coding_qual_input.txt");
        if (fileURL != null) {
            File file = new File(fileURL.getFile());
            try {
                BufferedReader in = new BufferedReader(new FileReader(file));
            }catch (FileNotFoundException e) {
                e.printStackTrace();
            }
        }
    }
}

I don't really know, if put the file correctly, but right now the new FileReader(file) gets me null.

So, why can't the FileReader read my file?

As Main.class.getResource("resources/coding_qual_input.txt") results in file:/C:/Users/Jonas/IdeaProjects/Android%20ATC/pyramidDecoder/out/production/pyramidDecoder/resources/coding_qual_input.txt, I don't see where the problem is.

Should I navigate somehow down the classpath?

Thanks for the help!

1

There are 1 best solutions below

0
Stefano Riffaldi On BEST ANSWER

ok, as I suspected, the space (%20) in the folder name seems to not be nice with URL, so I've recreated that behavior and got a FileNotFoundException (using Java 1.8)

Using ClassLoader.getSystemResourceAsStream all works fine, here's:

public static void main(String[] args) throws IOException {
    InputStream inputStream = ClassLoader.getSystemResourceAsStream("resources/coding_qual_input.txt");
    if (inputStream != null) {
        BufferedReader in = new BufferedReader(new InputStreamReader(inputStream));
        for (String line = in.readLine(); line != null; line = in.readLine()) {
            System.out.println(line);
        }
        in.close();
        inputStream.close();
    }
}

or (but I really discourage it) use String.replace to substitute "%20" with " " and still use URL

public static void main(String[] args) throws IOException {
    URL fileURL = Main.class.getResource("resources/coding_qual_input.txt");
    System.out.println(fileURL);
    if (fileURL != null) {
        File file = new File(fileURL.getFile().replace("%20", " "));
        BufferedReader in = new BufferedReader(new FileReader(file));
        for (String line = in.readLine(); line != null; line = in.readLine()) {
            System.out.println(line);
        }
        in.close();
    }
}

or (again, not the best way imho) use URL.openStream to directly open an InputStream without use File

InputStream inputStream = fileURL.openStream();
BufferedReader in = new BufferedReader(new InputStreamReader(inputStream));
for (String line = in.readLine(); line != null; line = in.readLine()) {
    System.out.println(line);
}