java - 使用 BufferedInputStream 下载无法正常工作

标签 java io download bufferedinputstream

以下代码无法下载文件(顺便说一句,clen 是文件的长度):

    int pos = 0, total_pos = 0;
    byte[] buffer = new byte[BUFFER_SIZE];
            while (pos != -1) {
                pos = in.read(buffer, 0, BUFFER_SIZE);
                total_pos += pos;
                out.write(buffer);
                setProgress((int) (total_pos * 100 / clen));
            }

...但这工作正常:

    int buf;
    while ((buf = in.read()) != -1)
        out.write(buf);

我想知道为什么,即使第二个代码段工作得很快。关于这一点,是否有任何特别的理由使用 byte[] 缓冲区(因为它似乎并不更快,而且 BufferedInputStream 已经使用了自己的缓冲区......?)

最佳答案

这是应该如何完成的。

public static void copyStream(InputStream is, OutputStream os)
    {
        byte[] buff = new byte[4096];
        int count;
        try {
            while((count = is.read(buff)) > 0)
                os.write(buff, 0, count);

        }catch (Exception e) {
            e.printStackTrace();
        }finally {
            try {
                if(is != null)
                    is.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            try {
                if(os != null)
                    os.close();
            } catch (IOException e) {
                e.printStackTrace();
            }

        }
    }

关于java - 使用 BufferedInputStream 下载无法正常工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7721167/

相关文章:

python - 从 EXPLOSM.net 漫画脚本下载 [Python]

java - Netbeans 将外部文件夹添加到项目中(如 Eclipse 上的链接文件夹)

java\r 字符在 Eclipse 中不起作用

java - 将指针传递给指针以通过 JNA 从 Java float 到 C 动态库

c - C 中的 fread/fwrite

android - 如何显示我的应用程序下载的文件列表?

java - 有没有办法让netbeans在编译时自动重启tomcat?

java - 单行文件大约 4G 加载到 Spark

file - 为什么 std::io::Read 中的函数需要缓冲区?

c# - WebClient.DownloadString(url) 不适用于第二个参数