[java][nio]MappedByteBuffer修改大文件

本文介绍了一种利用Java NIO中的MappedByteBuffer处理大文件的方法。通过实例演示了如何将大文件映射到内存中,并对其进行修改。示例程序创建了一个128MB的文件并用字符'x'填充,验证了映射缓冲区的有效性。


import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.nio.MappedByteBuffer;
import java.nio.channels.FileChannel;
/**
*
* MappedByteBuffer可用于对大文件的修改.
*
*/
public class LargeMappedFiles {

static int length = 128 * 1024 * 1024;//128m

public static void main(String[] args) throws FileNotFoundException, IOException {
RandomAccessFile file = new RandomAccessFile("d:\\a.txt","rw");
//MappedByteBuffer是特殊的直接缓冲器.必须指定文件的开始位置和文件大小.
MappedByteBuffer out = file.getChannel().map(FileChannel.MapMode.READ_WRITE, file.length(), length);
for(int i=0; i<length; i++){
out.put((byte)'x');
}
System.out.println("Finish writing.");
for(int i = length/2; i<(length/2 + 6); i++){
System.out.println((char)out.get(i));
}
file.close();
}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值