如何从网站下载整个文件

时间:2013-02-18 23:47:59

标签: java io inputstream

我举了这个例子: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();

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

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

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


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

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

2 个答案:

答案 0 :(得分:1)

InputStream.read()返回的值很重要,请使用它!

答案 1 :(得分:1)

不确定是否是原因,但您可以替换此

//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);
}

让我们知道它是怎么回事?

相关问题