One thing that is missing in Scala/Java standard library is a simple function loading a text file and returning it as a String. Of course this is not a way to deal with big files, but when you just need to load small and simple config file it would be useful.
Luckily, Apache commons provides such a function:
import org.apache.commons.io.IOUtils
import java.net.URL
def loadFromUrl(urlString: String): String = {
IOUtils.toString(new URL(urlString))
}
And as a bonus, you can use it for both local files and resources on the web as well.
loadFromUrl("file:///Users/foo/conf.json")
loadFromUrl("http://example.com/")
If you inspect the code of IOUtils
you will find that there is proper error handling, that means resources are closed in case of an exception. That part is usually missing in similar quick and simple solutions.
To use this, you need to add the following dependency:
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.4</version>
</dependency>
Top comments (0)