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")
In Java, we can use getResourceAsStream or getResource to read a file or multiple files from a resources folder or root of the classpath. The getResourceAsStream method returns an InputStream . // the stream holding the file content InputStream is = getClass(). getClassLoader().
We can either load the file(present in resources folder) as inputstream or URL format and then perform operations on them. So basically two methods named: getResource() and getResourceAsStream() are used to load the resources from the classpath. These methods generally return the URL's and input streams respectively.
Classpath in Java is not only used to load . class files, but also can be used to load resources e.g. properties files, images, icons, thumbnails, or any binary content. Java provides API to read these resources as InputStream or URL.
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 you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With