2017-08-03 69 views
0

我試圖從https:// URL下載使用Java文件時,現有的連接被強行關閉遠程主機,是它讓我返回這個錯誤:產生java.io.IOException:試圖下載文件

java.io.IOException: An existing connection was forcibly closed by the remote host

這裏是我使用的代碼:

URL website = new URL(fileUrl); 
File destinationFile = new File(toPath + returnFileNameFromUrl(fileUrl)); 
FileUtils.copyURLToFile(website, destinationFile); 

我已經嘗試過做這樣的:

try (InputStream inputStream = website.openStream(); 
    ReadableByteChannel rbc = Channels.newChannel(inputStream); 
    FileOutputStream fileOutputStream = new FileOutputStream(toPath + returnFileNameFromUrl(fileUrl))) { 
    fileOutputStream.getChannel().transferFrom(rbc, 0, Long.MAX_VALUE); 
    } 

但結果是一樣的。 我在做什麼錯?

我已經檢查過,URL可以從Chrome訪問,並且文件存在。

+0

什麼是'FileUtils'?標準的Java沒有這樣的類。 –

+0

https://commons.apache.org/proper/commons-io/javadocs/api-2.5/org/apache/commons/io/FileUtils.html –

+0

有沒有這樣的事情作爲一個https:\\ URL。反斜槓在URL中不合法。 – EJP

回答

0

雖然這是一個低一點的水平IO,它爲我工作,而無需使用第三方的依賴:

URL fileUrl = new URL("http://link.to/a.file"); 
    File dest = new File("local.file"); 
    try(InputStream inputStream = fileUrl.openStream(); 
     FileOutputStream outputStream = new FileOutputStream(dest)){ 
     byte[] buffer = new byte[64*1024]; 
     int readBytes; 
     while((readBytes = inputStream.read(buffer, 0, buffer.length))!=-1){ 
     outputStream.write(buffer, 0, readBytes); 
     } 
    } 
相關問題