ihmpall
ihmpall

Reputation: 1418

InputStream to a list in Scala

I am trying to read a file as input stream and then convert the contents of the file into a list in scala. Here is my code

val fileStream = getClass.getResourceAsStream("src/main/scala-2.11/com/dc/returnsModel/constants/abc.txt")
val item_urls = Source.fromInputStream(fileStream).getLines.toList

This does now work. I get a NullPointer Exception. How do I correct this?

However, this works(but I cant use it in a JAR File)

val item_urls = Source.fromFile("src/main/scala-2.11/com/dc/returnsModel/constants/aa.txt").getLines.toList

Upvotes: 0

Views: 1136

Answers (2)

Gaurav Abbi
Gaurav Abbi

Reputation: 645

You have to provide the correct path starting from root. Here root is start of your src/scala-2.11 folder in your case.

One example

object SO extends App {
  val resourceStream = SO.getClass.getResourceAsStream("/com/sm.txt")
  println(Source.fromInputStream(resourceStream).getLines.toList)
 }

Upvotes: 0

Tzach Zohar
Tzach Zohar

Reputation: 37852

getClass.getResourceAsStream does not expect a full path, it searches for the requested file in the classpath using the same class loader as the current class.

Fixing this depends a bit on the structure of your project and class that calls this code:

  • If the class returned by getClass is in the same package as the file you're trying to load (com.dc.returnsModel.constants), then you should simply reference the file name only:

    getClass.getResourceAsStream("abc.txt")
    
  • If the class returned by getClass resides in a different package, path should start with a / which represents the root of the classpath, hence the package name must follow:

    getClass.getResourceAsStream("/com/dc/returnsModel/constants/abc.txt")
    

Upvotes: 1

Related Questions