我的scala代码中的文件下载问题

时间:2011-03-10 10:20:58

标签: scala

我编写了以下scala代码来下载文件。文件正确下载,但也抛出异常。代码如下:

var out:OutputStream = null
var in:InputStream = null

      try {
        var url:URL = null
        url = new URL("http://somehost.com/file.doc")
        val uc = url.openConnection()
        val connection = uc.asInstanceOf[HttpURLConnection]
        connection.setRequestMethod("GET")
        val buffer:Array[Byte] = new Array[Byte](1024)
        var numRead:Int = 0
        in = connection.getInputStream()
        var localFileName="test.doc"
        out = new BufferedOutputStream(new FileOutputStream(localFileName))
        while ((numRead = in.read(buffer)) != -1) {
              out.write(buffer,0,numRead);
        }
      }
      catch {
        case e:Exception => println(e.printStackTrace())
      }

      out.close()
      in.close()

文件被下载但引发了以下异常:

java.lang.IndexOutOfBoundsException
    at java.io.FileOutputStream.writeBytes(Native Method)
    at java.io.FileOutputStream.write(FileOutputStream.java:260)
    at java.io.BufferedOutputStream.write(BufferedOutputStream.java:105)
    at TestDownload$.main(TestDownload.scala:34)
    at TestDownload.main(TestDownload.scala)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
    at java.lang.reflect.Method.invoke(Method.java:597)
    at com.intellij.rt.execution.application.AppMain.main(AppMain.java:115)
()

为什么会发生这种情况并以任何方式解决它?

请帮助 谢谢

2 个答案:

答案 0 :(得分:9)

Scala返回类型Unit,而不是赋值的类型,带有赋值语句。所以

numRead = in.read(buffer)

从不返回-1;它甚至不返回整数。你可以写

while( { numRead = in.read(buffer); numRead != -1 } ) out.write(buffer, 0, numRead)

或者您可以使用

寻找更实用的风格
Iterator.continually(in.read(buffer)).takeWhile(_ != -1).foreach(n => out.write(buffer,0,n))

就个人而言,我更喜欢前者,因为它更短(并且更少依赖迭代器评估“它应该”的方式)。

答案 1 :(得分:2)

另一种选择是使用系统命令,这些命令比我所说的更清晰,更快。

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

new URL("http://somehost.com/file.doc") #> new File("test.doc") !!