How to download and save a file from the internet using Scala?

前端 未结 4 735
礼貌的吻别
礼貌的吻别 2021-02-02 13:21

Basically I have a url/link to a text file online and I am trying to download it locally. For some reason, the text file that gets created/downloaded is blank. Open to any sugge

4条回答
  •  渐次进展
    2021-02-02 13:55

    Here is a safer alternative to new URL(url) #> new File(filename) !!:

    val url = new URL(urlOfFileToDownload)
    
    val connection = url.openConnection().asInstanceOf[HttpURLConnection]
    connection.setConnectTimeout(5000)
    connection.setReadTimeout(5000)
    connection.connect()
    
    if (connection.getResponseCode >= 400)
      println("error")
    else
      url #> new File(fileName) !!
    

    Two things:

    • When downloading from an URL object, if an error (404 for instance) is returned, then the URL object will throw a FileNotFoundException. And since this exception is generated from another thread (as URL happens to run on a separate thread), a simple Try or try/catch won't be able to catch the exception. Thus the preliminary check for the response code: if (connection.getResponseCode >= 400).
    • As a consequence of checking the response code, the connection might sometimes get stuck opened indefinitely for improper pages (as explained here). This can be avoided by setting a timeout on the connection: connection.setReadTimeout(5000).

提交回复
热议问题