0

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
ihmpall
  • 1,358
  • 2
  • 13
  • 17

2 Answers2

1

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")
    
Tzach Zohar
  • 37,442
  • 3
  • 79
  • 85
0

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)
 }
Gaurav Abbi
  • 645
  • 9
  • 23