2

I have directory structure like this

  • src

    • main
      • resources
        • text.txt
      • scala
        • hello
          • world.scala
    • test
      • same as main folder
  • pom.xml

When in IDE (Intellij10), I could access it with relative path ("src/main/resource/text.txt") but it seems I can not do that when I compile in jar. How to read that file ?

also, I found that test.txt is copy into root of jar. Is this normal behavior ? Since I fear this will be clash with other resources file in src/test/resources.

thanks

Tg.
  • 5,608
  • 7
  • 39
  • 52

2 Answers2

5

From http://www.java-forums.org/advanced-java/5356-text-image-files-within-jar-files.html -

Once the file is inside the jar, you cannot access it with standard FileReader streams since it is treated as a resource. You will need to use Class.getResourceAsStream().

The test.txt being copied into the root is not normal behavior and is probably a setting with your IDE.

Thomas
  • 151
  • 1
  • So about the location of resource files. What about maven ? I plan to use both so I want both of them behave the same way. I'm still struggle on how to read it the file in jar however. – Tg. Dec 01 '11 at 00:19
  • ok, got it. Although I feel weird that I have to deal with inputstream to read. Is this by design or something ? – Tg. Dec 01 '11 at 01:47
  • 1
    It is a logical limitation on the design. Once a file is inside the jar, you can't read it from the file system by a file path because it's not there. It's now a block of data inside a compressed archive. – Thomas Dec 01 '11 at 02:04
  • that's too bad. I hope for some universal method to process the file in jar and outside. I think I have to rethink the way I deploy jar file then. – Tg. Dec 03 '11 at 22:20
2

8 years later, I am also facing the same question. To ease the life of future developers, here is the answer:

Being copied into the root is normal behaviour, as:

the resources folder is like a src folder and so the content is copied, not the folder itself.

Now concerning the how-to question:

import scala.io.Source

val name = "text.txt"
val source: Source = Source.fromInputStream(getClass.getClassLoader.getResourceAsStream(name))
// Add the new line character as a separator as by getLines removes it
val resourceAsString:  String = source.getLines.mkString("\n")
// Don't forget to close
source.close
user1485864
  • 499
  • 6
  • 18