有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java如何从网站下载整个文件

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

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


共 (1) 个答案

  1. # 1 楼答案

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