Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

scala :How to read file in jar

Tags:

jar

scala

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

like image 889
Tg. Avatar asked Feb 02 '26 05:02

Tg.


2 Answers

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.

like image 137
Thomas Avatar answered Feb 04 '26 00:02

Thomas


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
like image 29
user1485864 Avatar answered Feb 03 '26 22:02

user1485864



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!