BufferOutputStream 的write方法

这段下载代码为何总是下载的文件不对?

public static int loadFile(File file, String RequestURL) {
                int result = 0;
                BufferedInputStream inputB = null;
                BufferedOutputStream outputB = null;
                try {
                        URL url = new URL(RequestURL);
                        URLConnection connect = url.openConnection();
                        InputStream input = connect.getInputStream();
                        FileOutputStream output = new FileOutputStream(file);
                        inputB = new BufferedInputStream(input);
                        outputB = new BufferedOutputStream(output);
                        byte[] buffer = new byte[1024];
                        int read = 0;
                        while ((read = inputB.read(buffer)) != -1) {
                                outputB.write(buffer);
                                outputB.flush();
                        }
                } catch (MalformedURLException e) {
                        e.printStackTrace();
                } catch (IOException e) {
                        e.printStackTrace();
                } finally {
                        try {
                                outputB.close();
                                inputB.close();
                        } catch (IOException e) {
                                e.printStackTrace();
                        }
                }
                return result;


        }


看了下JDK 发现了一点线索
下面是write(byte b) 方法的解释
The write method of FilterOutputStream calls its write method of three arguments with the arguments b, 0, and b.length. 

Note that this method does not call the one-argument write method of its underlying stream with the single argument b. 
其实这个方法好像是调用write3个参数的方法 放的参数是wtite(byte b, 0, b。length)
而buffer定义的长度是1024
write(buffer, 0, read);使用这个方法时 
我将read 和 buffer.length打印对比了下
1024---1024
1024---1024
1024---1024
1024---1024
1024---1024
1024---1024
1024---1024
1024---1024
1024---1024
1024---1024
1024---1024
126---1024
1024---1024
1024---1024
1024---1024
1024---1024
1024---1024
1024---1024
1024---1024
1024---1024
520---1024
1024---1024
1024---1024
1024---1024
1024---1024
1024---1024
1024---1024
1024---1024
1024---1024
1024---1024
948---1024
1024---1024
1024---1024
1024---1024
1024---1024
1024---1024
1024---1024
1024---1024
1024---1024
1024---1024
948---1024
207---1024
前面的是read的大小, 发现并不是每次读取数据都是1024个字节  所以写入的长度要用read来定 用buffer.length中间会有空着的地方

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值