[英]Download big file is too slow
我遇到这样的情况。
我的项目收到来自perl的下载请求
void downloadRequest(FileItemIterator items,
HttpServletResponse response) throws Exception
{
log.info("Start downloadRequest.......");
OutputStream os = response.getOutputStream();
File file = new File("D:\\clip.mp4");
FileInputStream fileIn = new FileInputStream(file);
//while ((datablock = dataOutputStreamServiceImpl.readBlock()) != null)
byte[] outputByte = new byte[ONE_MEGABYE];
while (fileIn.read(outputByte) != -1)
{
System.out.println("--------" + (i = i + 1) + "--------");
System.out.println(new Date());
//dataContent = datablock.getContent();
System.out.println("Start write " + new Date());
os.write(outputByte);
System.out.println("End write " + new Date());
//System.out.println("----------------------");
}
os.close();
}
}
我尝试从文件读取和写入1MB的块。 但是,下载整个文件花费的时间太长。 (对于100MB的文件,我的情况是20分钟)
我尝试sysout,结果如下:
前几个块可以真正快速地读取和写入数据:
--------1--------
Mon Dec 07 16:24:20 ICT 2015
Start write Mon Dec 07 16:24:20 ICT 2015
End write Mon Dec 07 16:24:21 ICT 2015
--------2--------
Mon Dec 07 16:24:21 ICT 2015
Start write Mon Dec 07 16:24:21 ICT 2015
End write Mon Dec 07 16:24:21 ICT 2015
--------3--------
Mon Dec 07 16:24:21 ICT 2015
Start write Mon Dec 07 16:24:21 ICT 2015
End write Mon Dec 07 16:24:21 ICT 2015
但是下一块比上一块慢
--------72--------
Mon Dec 07 16:29:22 ICT 2015
Start write Mon Dec 07 16:29:22 ICT 2015
End write Mon Dec 07 16:29:29 ICT 2015
--------73--------
Mon Dec 07 16:29:29 ICT 2015
Start write Mon Dec 07 16:29:29 ICT 2015
End write Mon Dec 07 16:29:37 ICT 2015
--------124--------
Mon Dec 07 16:38:22 ICT 2015
Start write Mon Dec 07 16:38:22 ICT 2015
End write Mon Dec 07 16:38:35 ICT 2015
--------125--------
Mon Dec 07 16:38:35 ICT 2015
Start write Mon Dec 07 16:38:35 ICT 2015
End write Mon Dec 07 16:38:48 ICT 2015
我真的不明白outputStream的写法,为什么要花这么长时间? 还是我犯了一些错误?
对不起,我的英语不好。 我真的需要您的支持。 预先感谢!
没有保证read(byte [] b)方法将从文件中读取b.length
个字节,这意味着您的代码发送的字节数可能比文件实际发送的字节数多。
例如,如果您正在处理10 MB的文件,而read(byte[] b)
始终从文件读取b.length/2
,则将发送20 MB。
为了解决这个问题,您可以执行以下操作。
byte[] outputByte = new byte[ONE_MEGABYE];
int r = -1;
while ((r = fileIn.read(outputByte)) != -1){
os.write(outputByte,0,r);
}
这将确保您仅发送与从文件读取的字节一样多的字节。
除了此问题之外,速度还可能受很多其他因素的影响,例如互联网速度或其他程序的实现。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.