2

Looking for best practice here. My app requires a few text files. I must use the following directory structure:

proj/src/main/java/com/foo/MyClass.java
proj/src/main/rsrc/File1.txt

I want to be able to run the app in Eclipse and from command line (maven-packaged into a jar), and it has to work under Windows and Linux.

  1. What do I need to do in terms of project config?
  2. How do I access the resource file in code?

Cheers

EDIT: minor rewording - directory structure is enforced from above.

seminolas
  • 407
  • 8
  • 15

4 Answers4

2

You can use the context classloader to grab to load them as a stream

Thread.currentThread().getContextClassLoader().getResourceAsStream("File1.txt");

henry
  • 5,923
  • 29
  • 46
  • 1
    https://www.youtube.com/watch?v=9-dDfgOprYU To summarize: In Eclipse add a "source directory" name it for example "assets", and copy the file there. Then: final InputStream myFile= Thread.currentThread().getContextClassLoader(). getResourceAsStream("myFile.txt"); – Oren Apr 29 '15 at 09:52
2

I would recommend using Apache Maven. This tool can automatically JAR up your project and include your resources. They have a quick tutorial on Maven in 5 minutes. Then all you need to do is place your resources in src.main.resources and it should automatically included in the jar (see the Getting Started Guide) for more details.

Hope this helps!

Update

As for getting the resource from here, have you tried getResourceAsStream() from the Java file?

Ascalonian
  • 14,409
  • 18
  • 71
  • 103
  • heh. the reason I asked this question was because (I thought) this didn't work. Of course, this morning it suddenly just works. Upvoting as it is the correct answer to the first half of the question. – seminolas Apr 03 '12 at 07:53
0
  1. You don't need any special project config. Creating a dedicated folder for you text file under src i think it's not so good as src is the folder of code sources. Personally i think putting inside src non source code files is not a best practice.
  2. I'll create a new directory for example DocDir, sibling of src. The in you java code under src you can access a file with:

    File file = new File("../../DocDir/File1.txt");

put the all ../ you need to toreach DocDir directory.

ab_dev86
  • 1,952
  • 16
  • 21
0

If *.txt files are not being included in your package, maybe you need to add some rules in your pom.xml, e.g.

<build>
    <resources>
        <resource>
            <directory>src/main/rsrc</directory>
            <filtering>true</filtering>
            <includes>
                <include>**/*.txt</include>
            </includes>
        </resource>
    </resources>
</build>
pires
  • 1
  • He doesn't say if he's using Maven. You may want to explain how to get started with Maven, as it's not the simplest thing to pick up and start using. – Thorn G Apr 02 '12 at 20:16
  • @TomG in fact I do say I'm using maven, although not very explicitly. – seminolas Apr 03 '12 at 07:44