InputStream 二进制读取文件, byte数据的长度问题

来源:互联网 发布:php菱形 编辑:程序博客网 时间:2024/05/16 15:42

 

当读取文件为如下方式的时候,

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);    }


0 0
原创粉丝点击