34

Is there a one-liner in Scala to read a file from classpath without using external dependencies, e.g. commons-io?

IOUtils.toString(getClass.getClassLoader.getResourceAsStream("file.xml"), "UTF-8")
Jacek Laskowski
  • 72,696
  • 27
  • 242
  • 420
mbdev
  • 6,343
  • 14
  • 46
  • 63
  • 2
    By not having dependency on commons-io or by not using classloader. Maybe by supporting syntax like Spring "classloader:..." – mbdev May 25 '11 at 10:25

4 Answers4

61
val text = io.Source.fromInputStream(getClass.getResourceAsStream("file.xml")).mkString

If you want to ensure that the file is closed:

val source = io.Source.fromInputStream(getClass.getResourceAsStream("file.xml"))
val text = try source.mkString finally source.close()
GreenGiant
  • 4,930
  • 1
  • 46
  • 76
dacwe
  • 43,066
  • 12
  • 116
  • 140
  • 3
    Note this will leave the file handle to file.xml open, even after the string has been produced. – pdxleif Apr 14 '14 at 21:31
  • This didn't work for me.. I get a null input stream while file is on class path. – Cheruvim Jun 27 '23 at 03:35
  • What did work for me is using the class loader instead: `io.Source.fromInputStream(getClass.getClassLoader.getResourceAsStream("file.xml")) ` – Cheruvim Jun 27 '23 at 03:39
10

If the file is in the resource folder (then it will be in the root of the class path), you should use the Loader class that it is too in the root of the class path.

This is the code line if you want to get the content (in scala 2.11):

val content: String  = scala.io.Source.fromInputStream(getClass.getClassLoader.getResourceAsStream("file.xml")).mkString

In other versions of Scala, Source class could be in other classpath

If you only want to get the Resource:

val resource  = getClass.getClassLoader.getResource("file.xml")
fhuertas
  • 4,764
  • 2
  • 17
  • 28
2

Just an update, with Scala 2.13 it is possible to do something like this:

import scala.io.Source
import scala.util.Using

Using.resource(getClass.getResourceAsStream("file.xml")) { stream =>
  Source.fromInputStream(stream).mkString
}

Hope it might help someone.

0

In Read entire file in Scala? @daniel-spiewak proposed a bit different approach which I personally like better than the @dacwe's response.

// scala is imported implicitly
import io.Source._

val content = fromInputStream(getClass.getResourceAsStream("file.xml")).mkString

I however wonder whether or not it's still a one-liner?

Community
  • 1
  • 1
Jacek Laskowski
  • 72,696
  • 27
  • 242
  • 420