ByteBuffer读大文件以及组装

来源:互联网 发布:狼图腾知乎 编辑:程序博客网 时间:2024/06/08 00:33
public String mappedBuffer(String file) throws IOException{            FileChannel read = new FileInputStream(file).getChannel();            long i = 0;        long size = read.size()/30;            ByteBuffer bb = null;        ByteBuffer temp = null, all = null;                while(i<read.size()&&(read.size()-i)>size){        bb = ByteBuffer.allocate((int)size);             bb = bb.put(read.map(FileChannel.MapMode.READ_ONLY, i, size));            if (all!=null){            temp = ByteBuffer.allocate(all.limit());             temp = temp.put(all.array());            }            if (all==null){            all = ByteBuffer.allocate(bb.limit());            }else{            all = ByteBuffer.allocate(temp.limit()+bb.limit());            }            all.clear();            if (temp!=null){            all = all.put(temp.array());            }            all = all.put(bb.array());            i+=size;                        bb.clear();            if (temp!=null){            temp.clear();            }        }        bb = ByteBuffer.allocate((int)(read.size()-i));         bb = bb.put(read.map(FileChannel.MapMode.READ_ONLY, i, read.size()-i));        if (all!=null){        temp = ByteBuffer.allocate(all.limit());         temp = temp.put(all.array());        }        if (all==null){        all = ByteBuffer.allocate(bb.limit());        }else{        all = ByteBuffer.allocate(temp.limit()+bb.limit());        }        all.clear();        if (temp!=null){        all = all.put(temp.array());        }        all = all.put(bb.array());                all.flip();        Charset charset=Charset.forName("GBK");        String bufData = charset.decode(all).toString();        //System.out.println("====bufData="+bufData);                bb.clear();        if (temp!=null){        temp.clear();        }        read.close();        return bufData;    }   

0 0
原创粉丝点击