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;
}
ByteBuffer读大文件以及组装
最新推荐文章于 2022-10-14 16:34:27 发布