2011-03-10 41 views
2

我已經編寫了下面的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) 
() 

爲什麼會這樣發生,什麼辦法來解決呢?

請幫助 謝謝

回答

9

斯卡拉返回類型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)) 

就個人而言,我更喜歡前者,因爲它是短(和迭代評估依賴較少發生的方法「應然「)。

+0

感謝雷克斯,工作! :) – tomrs 2011-03-10 10:50:44

2

另一種選擇是使用系統命令,它比我所能說的更清晰和更快。

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

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