java mapfile_java Memorymapfile demo

importjava.io.File;importjava.io.IOException;importjava.io.RandomAccessFile;importjava.nio.CharBuffer;importjava.nio.channels.FileChannel;importjava.nio.channels.FileChannel.MapMode;public classmemorymapfiledemo {final static String filepath = "/home/hadoop/test/java.txt";public static void main(String[] args) throwsIOException {

writefile(filepath);

readfile(filepath);

}static void writefile(String _filepath) throwsIOException {

File _file= newFile(_filepath);

RandomAccessFile raf= new RandomAccessFile(_file, "rw");

FileChannel fc=raf.getChannel();int buffersize = 1024 * 8;

CharBuffer cb= fc.map(MapMode.READ_WRITE, 0, buffersize)

.asCharBuffer();

String lineseperator=java.security.AccessController

.doPrivileged(newsun.security.action.GetPropertyAction("line.separator"));

String content= "";long offset = 0;for (int i = 1; i <= 1000; i++) {

content= "Line" + i + " hello java" +lineseperator;if ((cb.limit() - cb.position())

offset+=cb.position();

cb=fc.map(MapMode.READ_WRITE, offset, buffersize)

.asCharBuffer();

}

cb.put(content);

}

fc.close();

raf.close();

}static void readfile(String _filepath) throwsIOException {

File _file= newFile(_filepath);

RandomAccessFile raf= new RandomAccessFile(_file, "rw");

FileChannel fc=raf.getChannel();long totalsize =fc.size();int buffersize = 1024 * 8;long offset = 0;

CharBuffer cb= fc.map(MapMode.READ_ONLY, 0, buffersize).asCharBuffer();while (offset

System.out.print(cb.get());

}

offset+=cb.position();

cb=fc.map(MapMode.READ_ONLY, offset, buffersize).asCharBuffer();

}

fc.close();

raf.close();

}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值