如何在java中下载大型文件(大小> 50MB)

我正在从远程位置下载文件,对于较小尺寸的文件,下载完成,对于大尺寸文件(> 10 MB),下载完成。 这是我用来从远程服务器下载文件的代码。

File dstFile = null; // check the directory for existence. String dstFolder = LOCAL_FILE.substring(0,LOCAL_FILE.lastIndexOf(File.separator)); if(!(dstFolder.endsWith(File.separator) || dstFolder.endsWith("/"))) dstFolder += File.separator; // Creates the destination folder if doesn't not exists dstFile = new File(dstFolder); if (!dstFile.exists()) { dstFile.mkdirs(); } try { URL url = new URL(URL_LOCATION); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.addRequestProperty("User-Agent", "Mozilla/4.76"); //URLConnection connection = url.openConnection(); BufferedInputStream stream = new BufferedInputStream(connection.getInputStream()); int available = stream.available(); byte b[]= new byte[available]; stream.read(b); File file = new File(LOCAL_FILE); OutputStream out = new FileOutputStream(file); out.write(b); } catch (Exception e) { System.err.println(e); VeBLogger.getInstance().log( e.getMessage()); } 

您可以使用apache commons IO库 。 这很简单。 我在很多项目中都使用过它。

 File dstFile = null; // check the directory for existence. String dstFolder = LOCAL_FILE.substring(0,LOCAL_FILE.lastIndexOf(File.separator)); if(!(dstFolder.endsWith(File.separator) || dstFolder.endsWith("/"))) dstFolder += File.separator; // Creates the destination folder if doesn't not exists dstFile = new File(dstFolder); if (!dstFile.exists()) { dstFile.mkdirs(); } try { URL url = new URL(URL_LOCATION); FileUtils.copyURLToFile(url, dstFile); } catch (Exception e) { System.err.println(e); VeBLogger.getInstance().log( e.getMessage()); } 

首先,我建议你使用:

 FileInputStream in = new FileInputStream(file); 

代替:

 BufferedInputStream in = new BufferedInputStream(new FileInputStream(file)); 

(为避免增加内存使用量)

 try { FileInputStream fileInputStream = new FileInputStream(file); byte[] buf=new byte[8192]; int bytesread = 0, bytesBuffered = 0; while( (bytesread = fileInputStream.read( buf )) > -1 ) { out.write( buf, 0, bytesread ); bytesBuffered += bytesread; if (bytesBuffered > 1024 * 1024) { //flush after 1MB bytesBuffered = 0; out.flush(); } } } finally { if (out != null) { out.flush(); } } 

请阅读API中的BufferedInputStream方法.available()。

它返回已下载的可用字节数(即,无需访问/等待网络即可从流中读取的字节数)。

您应该创建一个固定大小的字节数组fx。 2048字节,并使用read()方法,直到它返回-1。