java 完美读取字节流 实例

来源:互联网 发布:mac贴膜会影响散热吗 编辑:程序博客网 时间:2024/05/17 23:07

在使用BufferedInputStream读取字节流是,若最后剩余的字节数,小于指定读取的字节数,则返回的字节数组的内容长度仍然是指定的字节数,这时若写入新的文件,或者写

入socket时,则会出现目标文件比原文件多几个字节,并不是和原文件一模一样的大小。下面的例子可以完美的解决这个问题。^_^

@Overridepublic void run() {try {FileInputStream fis = null;BufferedInputStream bis = null;fis = new FileInputStream(filepath);if (fis != null) {bis = new BufferedInputStream(fis);}if (bis != null) {byte[] bs = new byte[512];while(bis.available() > 512) {bis.read(bs);ByteBuffer src = ByteBuffer.wrap(bs);// write data to client socket channellsockChannel.write(src);Arrays.fill(bs, (byte)0);}// 处理不足512的剩余部分int remain = bis.available(); byte[] last = new byte[remain];bis.read(last);lsockChannel.write(ByteBuffer.wrap(last));                bis.close();fis.close();lsockChannel.close();}} catch (Exception e) {e.printStackTrace();}}