How to read a file from classpath without external dependencies?

mbdev picture mbdev · May 25, 2011 · Viewed 27.1k times · Source

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")

Answer

dacwe picture dacwe · May 25, 2011
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()