1
Package
|
|------src/main/java
|------resources
            |---- config.properties

In pom.xml, I have set resoucres directory as follows

<resources>
        <resource>
            <directory>resources</directory>
        </resource>
</resources>

I'm able to get the absolute path of the file. But When I try to read or check whether it is a file or directory, it is return false.

sample.java

File configFile =  new File("config.properties");               
        System.out.println("PATH="+newFile.getAbsolutePath());
        System.out.println("IsFile="+newFile.isFile());
       System.out.println("CanRead="+configFile.canRead());

Output

PATH=D:\JCB\MyWorkSpace_LunaJEE\MessageProcessor\config.properties
IsFile=false
CanRead=false

Any help will be appreciated.

Naghaveer R
  • 2,890
  • 4
  • 30
  • 52

2 Answers2

1

The file is not in D:\JCB\MyWorkSpace_LunaJEE\MessageProcessor\config.properties, but in the resources folder there, so it does not exist and thus is neither file nor directory. I would suggest putting it in /src/main/resources and then accessing it via getResourceAsStream( name );

Florian Schaetz
  • 10,454
  • 5
  • 32
  • 58
1

In pom.xml, I have set resoucres directory as follows

That defines the directory where resources will be stored as part of the Maven build structure - so it specifies where Maven should look for resource files to include in your program. It does not define where files can be found when running your application. It is not really a good idea to change from the Maven conventions, keep it as src/main/resources if you can. If you use external tooling on top of Maven, you may get conflicts otherwise.

What is the important part is what happens with the files when the application is built by Maven when you do for example a mvn clean install.

whatever is in src/main/java is compiled and the classes are put in the target directory, in their proper package structure. The files and directories in the src/main/resources folder are copied to that same target directory. The resources are thus made part of your Java program and are available on the classpath; if you would let Maven build your application into an executable jar at this point for example, the resources will be packaged together with the classes inside that jar.

To properly load the resource files packaged with your application, you should use Java's classloader system. This question's answer demonstrates that in detail. To change your current test code, you would rather do something like this:

InputStream is = getClass().getClassLoader().getResourceAsStream("config.properties");

if(is != null){
  // yep, the file exists on the classpath! Now load it with the InputStream
}
Community
  • 1
  • 1
Gimby
  • 5,095
  • 2
  • 35
  • 47