如何从网站下载整个文件 [英] How to download whole file from website

查看:346
本文介绍了如何从网站下载整个文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我举了这个例子: http:/ /www.mkyong.com/java/how-to-download-file-from-website-java-jsp

File file = new File("path/to/file/test.txt");
FileInputStream fis= new FileInputStream(file);
ServletOutputStream out = response.getOutputStream();

byte[] outputByte = new byte[4096];
//copy binary contect to output stream
while(fis.read(outputByte, 0, 4096) != -1)
{
    out.write(outputByte, 0, 4096);
}
fis.close();
out.flush();
out.close();

问题是下载文件仍然不完整。在文件的末尾仍然缺少一些字符

problem is that download file is still incomplete. At the end of file there is still missing some characters

所以我尝试了另一个例子:

so I try another example:

File file = new File("path/to/file/test.txt");
FileInputStream fis= new FileInputStream(file);


IOUtils.copy(fis,response.getOutputStream());
fis.close();

下载文件已完成。所以我的问题是为什么第一个例子不起作用,第二个例子是正确的

download file is complete. So my question is why first example doesnt work and is second example is correct

推荐答案

不确定这是否是原因但是你可以更换这个

Not sure if that is cause but could you replace this

//copy binary contect to output stream
while(fis.read(outputByte, 0, 4096) != -1)
{
    out.write(outputByte, 0, 4096);
}

int length=-1;
while ( (length = fis.read(outputByte, 0, 4096)) != -1) {
    out.write(outputByte, 0, length);
}

告诉我们怎么回事?

这篇关于如何从网站下载整个文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆