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")
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()
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")
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.
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?
精彩评论