0

I have a java project in Eclipse. I want a read file that is in a certain folder. I use this code:

File file = new File("directory/filename.txt");

If I have a simple java project, with this layout:

Project
|
+- src
+- lib
+- directory
   |
   + filename.text

The code works fine and I can read the file. If I now convert this project to a maven project, Not much changes in Eclipse except a pom.xml file is made and a target folder is added (revaling the previously hidden "bin" output folder which is now a regular folder. The layout becomes:

Project
|
+- src
+- lib
+- bin
+- target
+- directory
|  |
|  + filename.text
+- pom.xml

Because I want to use the maven project setup, I removed the src folder and added 4 new source folders to my project in Eclipse:

Source folders

I copied the filename.text to the resources folder, which should automaticcaly put its content on the classpath. My project layout becomes:

Project
|
+- src/main/java
+- src/main/resources
|   |
|   + filename.text
+- src/test/java
+- src/test/resources
+- lib
+- bin
+- target
+- pom.xml

Now I noticed that this code doesn't work (NoSuchFileException)

File file = new File("filename.txt");

But this code does work:

File file = new File("src/main/resources/filename.txt");

Note: the way I run my code is by running it in eclipse as a java project. The file read code is a single line in my main method in my main class.

I'm wondering what configuration I missed so that eclipse/maven regards the src/main/resources folder to be at the root of my classpath, rather than just a random folder that I have to explicitly name. It's especially weird, because another file in the resources folder, namely log4j.properties, is found and used by my log4j library without any problems.

Note: If I build my project and install it in my local repository, I can actually see both files (filename.txt and log4j.properties) being neatly under target/classes.

user1884155
  • 3,616
  • 4
  • 55
  • 108
  • If you want to read a file from the classpath you must use it as a resource. If you want to read it from the filesystem you must provide an actual path. – Dave Newton Dec 01 '15 at 12:33
  • check out this question: http://stackoverflow.com/questions/1464291/how-to-really-read-text-file-from-classpath-in-java – Jack Dec 01 '15 at 12:33
  • @ Dave Newton: How do I use a file as a resource? – user1884155 Dec 01 '15 at 12:59

1 Answers1

0

On your project:

Right-Click > Properties > Java build Path > Source : if you have some thing like :

enter image description here Right-Click > Properties > Deployement Assembly : check if you have some thing like:

enter image description here

Hope this helps.

jmj
  • 649
  • 8
  • 17