我的 Scala 代码中的文件下载问题 [英] File download problem in my scala code
问题描述
我编写了以下 Scala 代码来下载文件.该文件被正确下载,但也会引发异常.代码如下:
I have written the following scala code to download a file . The file gets downloaded correctly but also an exception is thrown. The code is as follows :
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()
文件已下载,但引发以下异常:
The file gets downloaded but the following exception is thrown :
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)
()
为什么会发生这种情况以及有什么方法可以解决?
Why could this be happening and any way to fix it ?
请帮忙谢谢
推荐答案
Scala 使用赋值语句返回类型 Unit
,而不是被赋值的值的类型.所以
Scala returns type Unit
, not the type of the value being assigned, with an assignment statement. So
numRead = in.read(buffer)
never 返回 -1
;它甚至不返回整数.你可以写
never returns -1
; it doesn't even return an integer. You can write
while( { numRead = in.read(buffer); numRead != -1 } ) out.write(buffer, 0, numRead)
或者你可以选择更实用的风格
or you can go for a more functional style with
Iterator.continually(in.read(buffer)).takeWhile(_ != -1).foreach(n => out.write(buffer,0,n))
就我个人而言,我更喜欢前者,因为它更短(并且更少依赖迭代器评估以它应该"的方式发生).
Personally, I prefer the former since it's shorter (and relies less on iterator evaluation happening the way "it ought to").
这篇关于我的 Scala 代码中的文件下载问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!