By Alvin Alexander. Last updated: June 24, 2016
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 java.net._ import java.io._ 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 } in.close buffer.foreach(println)
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.