How to read a file URL in Java and Scala

I thought this might be harder, but if you have a file URL like “file:///Users/al/SherlockHolmes.txt”, and want to read those file contents as a Java URL, the process in Java and Scala is simple, as shown in this Scala code:

import scala.collection.mutable.ArrayBuffer

val url = new URL("file:///Users/al/Desktop/50-Shades-Quotes.txt")
val in = new BufferedReader(new InputStreamReader(url.openStream))
val buffer = new ArrayBuffer[String]()
var inputLine = in.readLine
while (inputLine != null) {
    if (!inputLine.trim.equals("")) {
        buffer += inputLine.trim
    inputLine = in.readLine


That source code shows how to open, read, and process the contents of the file as a URL in Scala, but if you’re familiar with Java, you can see that the code is very similar, except for a few minor changes.

Add new comment

The content of this field is kept private and will not be shown publicly.

Anonymous format

  • Allowed HTML tags: <em> <strong> <cite> <code> <ul type> <ol start type> <li> <pre>
  • Lines and paragraphs break automatically.
By submitting this form, you accept the Mollom privacy policy.