0

I don't know how to properly access files from java when using maven. I know there are a lot of other questions/answers out there very similar to this but i haven't been able to get any of them to work for me.

Right now i have the code file i hope to be opening the data files with in this directory:

maven_project/src/main/java/project/package/source_file.java

in the pom.xml i'm including the resources like so:

<build>
  <resources>
    <resource>
      <directory>src/main/resources/question_contents</directory>
        <includes>
          <include>*.json</include>
        </includes>
     </resource>
  </resources>
</build>

The resource files are correctly being coppied to

 maven_project/target/classes

the command i'm using to build right now is

 mvn package

If it matters, i'm using linux

I am willing to change any aspect of this setup in order to open files.

I would prefer to open them as a FileInputStream but i can work with anything.

Any help would be much appreciated.

Update

I tried the answers in the suggested duplicate question, still no luck. Something that i didn't think about before was that this is being done in a method in a abstract class, idk what impact that would have on the refrences to this .

Also i know this worked at one point. Before moving everything to maven i had everything lumped in one folder, there were no issues.

jmoggr
  • 277
  • 2
  • 4
  • 8
  • 1
    Why are you add the resources configuration which is already default so no need to do so. – khmarbaise May 05 '15 at 07:29
  • possible duplicate of [How to really read text file from classpath in Java](http://stackoverflow.com/questions/1464291/how-to-really-read-text-file-from-classpath-in-java) – Joe May 05 '15 at 07:46

2 Answers2

3

Since you set up Maven to properly include the resource files in your build, you can access them using the class loader

InputStream in = 
  SomeClassInTheSamePackage.class.getResourceAsStream("filename.json");

// or using full path starting from slash

in = SomeClassAnywhereInYourProject.class.getResourceAsStream(
    "/question_contents/filename.json");
Thilo
  • 257,207
  • 101
  • 511
  • 656
1

getClassLoader() will help you in getting the file. Include the file in resources folder in maven project and use following to read the file.

BufferedReader br = new BufferedReader(new InputStreamReader(MyClass.class.getClassLoader().getResourceAsStream(fileName), "UTF8"));

Replace fileName with your actual fileName. Now, you can use br to read file line-by-line.

Abhishek
  • 6,912
  • 14
  • 59
  • 85
  • `Errors, filename.json does not exist` That's all i see. Everything else works. – jmoggr May 05 '15 at 08:18
  • Can you check if you have placed `filename.json` in resources folder? Also, please share your project folder structure in expanded mode by editing the question – Abhishek May 05 '15 at 08:36