DEV Community

Adam Cervenka
Adam Cervenka

Posted on

Quickly read file or any url in Scala/Java

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))
}
Enter fullscreen mode Exit fullscreen mode

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/")
Enter fullscreen mode Exit fullscreen mode

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>
Enter fullscreen mode Exit fullscreen mode

Top comments (0)