Search code examples
javamavenintellij-idea

JetBrains IntelliJ IDEA doesn't recognize resources folder


Recently, I tried to start a Maven project in InjelliJ IDEA. As you can see when I provide filePath as "data.txt" it doesn't find it and if I use file2.createNewFile() it'll make a new file at ini-parse folder that I don't want to. I want it to be in the resources folder. What should I do?

enter image description here

I've tried mark and unmarking it as resources folder but doesn't work.


Solution

  • resources folder is a concept introduced by the build tool maven. Java doesn't accord any special treatment for resources folder. When the program is executed, project root folder is considered the working directory. That's why you must provide a complete relative path from the working directory to be able to access the file.

    If your need is to read the file then there is an option that allows you not to provide complete file path. As the resources folder is added to the classpath by maven, you can read the file without the need to prefix the path with src\main\resources as shown below.

    InputStream in = this.getClass().getResourceAsStream("/data.txt");

    Hope this clarifies.