我已經編寫了下面的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)
()
爲什麼會這樣發生,什麼辦法來解決呢?
請幫助 謝謝
感謝雷克斯,工作! :) – tomrs 2011-03-10 10:50:44