Luigimax
Luigimax

Reputation: 546

Scala and html: download an image (*.jpg, etc) to Hard drive

I've got a Scala program that downloads and parses html. I got the links to the image files form the html, Now I need to transfer those images to my hard drive. I'm wondering what the best Scala method I should use.

my connection code:

import java.net._
import java.io._
import _root_.java.io.Reader
import org.xml.sax.InputSource

import scala.xml._

def parse(sUrl:String) = {
    var url = new URL(sUrl)
    var connect = url.openConnection

    var sorce:InputSource = new InputSource
    var neo = new TagSoupFactoryAdapter //load sUrl
    var input = connect.getInputStream

    sorce.setByteStream(input)
    xml = neo.loadXML(sorce)
    input.close
}

My blog

Upvotes: 2

Views: 2570

Answers (3)

bryanlcampbell
bryanlcampbell

Reputation: 71

An alternative option is to use the system commands which is much cleaner

import sys.process._
import java.net.URL
import java.io.File

object Downloader {
  def start(location: String) : Unit = {
    val url = new URL(location)

    var path = url match {
      case UrlyBurd(protocol, host, port, path) => (if (path == "") "/" else path)
    }

    path = path.substring(path.lastIndexOf("/") + 1)

    url #> new File(path) !!
  }
}

object UrlyBurd {
  def unapply(in: java.net.URL) = Some((
    in.getProtocol, 
    in.getHost, 
    in.getPort,
    in.getPath
  ))
}

Upvotes: 2

Ekkmanz
Ekkmanz

Reputation: 472

Then you may want to take a look at java2s. Although the solution is in plain Java but you can still modify to Scala syntax to "just use it"

Upvotes: 3

GClaramunt
GClaramunt

Reputation: 3158

One way to achieve that is: collect the URLs of the images and ask for them to the server (open a new connection with the image url and store the bytestream in the hard drive)

Upvotes: 0

Related Questions