我在java中有一个方法,可以从web上下载文件,但是通过java代码下载比我使用任何浏览器下载都要慢。
我的代码如下:
public void downloadFile(String downloadURL) {
System.out.println("Starting file download .....");
BufferedInputStream in = null;
FileOutputStream fout = null;
try {
URL u = new URL(downloadURL);
HttpURLConnection uc = (HttpURLConnection) u.openConnection();
String fileName = uc.getHeaderField("Content-Disposition");
fileName = YouTubeDownloader.parseResponse(fileName, "filename=\"", "\"");
System.out.println(fileName);
if (uc.getHeaderField("Content-Length") == null) {
System.out.println("File Length zero!!!!");
}
float fileSize = Float.parseFloat(uc.getHeaderField("Content-Length"));
in = new BufferedInputStream(uc.getInputStream());
System.out.println("File size : " + fileSize);
fout = new FileOutputStream("c:\\Dinesh\\" + fileName);
byte data[] = new byte[1024];
int count = 0;
int downloaded = 0;
while ((count = in.read(data, 0, 1024)) != -1) {
downloaded += count;
int downloadPercentage = (int) ((downloaded / fileSize) * 100);
System.out.println(downloadPercentage);
fout.write(data, 0, count);
}
System.out.println("File download completed.....");
} catch (Exception e) {
System.out.println(e);
}
}下载速度太慢是不是因为缓冲区太小了?
我是否可以增加缓冲区大小,或者如何优化以降低下载速度?
我需要修改什么东西?
提前谢谢。
发布于 2013-03-20 20:45:47
如果您不需要监控进度,请尝试以下操作:
Path saveFile = Paths.get("C:\\Dinesh", fileName);
Files.copy(uc.getInputStream(), saveFile);https://stackoverflow.com/questions/15498246
复制相似问题