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

Sentry image

Hands-on debugging session: instrument, monitor, and fix

Join Lazar for a hands-on session where you’ll build it, break it, debug it, and fix it. You’ll set up Sentry, track errors, use Session Replay and Tracing, and leverage some good ol’ AI to find and fix issues fast.

RSVP here →

Top comments (0)

Heroku

This site is built on Heroku

Join the ranks of developers at Salesforce, Airbase, DEV, and more who deploy their mission critical applications on Heroku. Sign up today and launch your first app!

Get Started

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay