InputStream 二进制读取文件, byte数据的长度问题
当读取文件为如下方式的时候,
File file = new File(path); FileInputStream is = new FileInputStream(file); try { byte[] temp = new byte[1024]; while (is.read(temp) > 0) { os.write(temp); } }
在读取得到最后一个temp 的时候temp的长度是1024 同时,temp里边存的可能是最后一次和倒数第二次的结合体, 因为最后一次的长度为n(0<n <1024>)的时候,0-n为最后一次读取到的, n+1-1024为倒数第二次的数据. 可以修改成这样
File file = new File(path); FileInputStream is = new FileInputStream(file); try { byte[] temp = new byte[1024]; int len; while ((len=is.read(temp)) > 0) { os.write(temp, 0, len); }
声明:该文观点仅代表作者本人,牛骨文系教育信息发布平台,牛骨文仅提供信息存储空间服务。