DEV Community

Adam Cervenka
Adam Cervenka

Posted on

1

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

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

Top comments (0)

👋 Kindness is contagious

Dive into an ocean of knowledge with this thought-provoking post, revered deeply within the supportive DEV Community. Developers of all levels are welcome to join and enhance our collective intelligence.

Saying a simple "thank you" can brighten someone's day. Share your gratitude in the comments below!

On DEV, sharing ideas eases our path and fortifies our community connections. Found this helpful? Sending a quick thanks to the author can be profoundly valued.

Okay