android下载的文件比服务器的文件大的原因与解决方案

来源:互联网 发布:阿里旺旺mac版如何退出 编辑:程序博客网 时间:2024/05/22 04:32

最近学习android时写了一个在web服务器下载文件的程序,程序能够下载成功,但是下载下来发现下载的文件比服务器上的文件大,

后来发现问题出现在往sdcard写入的一段程序:

 output = new FileOutputStream(file); byte buffer[] = new byte[8*1024]; while(input.read(buffer) != -1){    output.write(buffer); } output.flush();

上面定义的buffer不一定每次都能在执行 read(buffer) 时填充完整

 output = new FileOutputStream(file); byte buffer[] = new byte[8*1024]; int length = 0; while((length=input.read(buffer)) != -1){    output.write(buffer,0,length); } output.flush();

改写后,在调用write方法时指定了每次写的大小必须与每次读到的大小一致,这样问题就解决了

原创粉丝点击