2017-08-03 107 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); 
     } 
    } 
相关问题