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

前端 未结 4 690
礼貌的吻别
礼貌的吻别 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:33

    Here is a naive implementation by scala.io.Source.fromURL and java.io.FileWriter

    def downloadFile(token: String, fileToDownload: String) {
      try {
        val src = scala.io.Source.fromURL("http://randomwebsite.com/docs?t=" + token + "&p=tsr%2F" + fileToDownload)
        val out = new java.io.FileWriter("src/test/resources/testingUpload1.txt")
        out.write(src.mkString)
        out.close
      } catch {
        case e: java.io.IOException => "error occured"
      }
    }
    

    Your code works for me... There are other possibilities that make empty file.

提交回复
热议问题