Intellij - Not able to read a file from other package in the same module

Answered

I am using Intellij Idea - 2021.3.2 and Java 8. In Intellij, I am not able to read a file in another package in the same module. The file is under main and not resource folder. But in Eclipse, I am able to read.

For example. Below code prints different outputs in both eclipse and intellij.

import java.net.URL;

public class TestMain {
    public static void main(String[] args) {
        URL resource = TestMain.class.getResource("/org/files/input.txt");
        if(resource == null) {
            System.out.println("Resource is null");
        } else {
            System.out.println("Resource found!!");
        }
    }
}

Project Structure

 

In Intellij, the code prints "Resource is null", but in eclipse, the code prints "Resource found!!".

Is there any setting I need to enable/disable in intellij ? Why code is behaving different in Intellij Idea ?

0
4 comments

Move the file into resources/org/files.

.txt files are not copied to classpath from the source roots by Maven conventions.

If you want to copy these files from the source roots, you need to adjust pom.xml configuration: https://stackoverflow.com/a/23289401/104891.

Eclipse is not following the conventions and you will get different results in command line Maven and in the IDE, which is bad.

0

Unfortunately, most of the code is developed using eclipse and now we are migrating the development process to Intellij.  We are using gradle not maven.  I will look in to the stackoverflow thread you mentioned and update.

0

Your screenshot shows pom.xml file in the project root, so I assumed you were using Maven.

Gradle has similar conventions, so the same would apply.

Imagine your build works fine in the IDE, but production build is done on CI server and the results are different, that is why IDE should always follow the conventions of the build system.

0

Sorry for the confusion. I just created a sample project in my local machine to show the scenario. I understand your point. 

0

Please sign in to leave a comment.