java 数据以eof结束,使用NIO(Java)在EOF之后重新读取文件

I'm using MemoryMapped buffer to read a file. Initially I'm getting the channel size and using the same size I"m mapping the file on memory and here the initial position is 0 as I want to map the file from the beginning. Now another 400KB of data is added to that file, now I want to map that 400kb alone. But something is wrong in my code, I'm not able to figure it out and I'm getting this

260java.io.IOException: Channel not open for writing - cannot extend file to required size

at sun.nio.ch.FileChannelImpl.map(FileChannelImpl.java:812)

at trailreader.main(trailreader.java:55

So here's my code

BufferedWriter bw;

FileInputStream fileinput = null;

try {

fileinput = new FileInputStream("simple.csv");

} catch (FileNotFoundException e1) {

// TODO Auto-generated catch block

e1.printStackTrace();

}

FileChannel channel = fileinput.getChannel();

MappedByteBuffer ByteBuffer;

try {

ByteBuffer = fileinput.getChannel().map(FileChannel.MapMode.READ_ONLY, 0, channel.size());

} catch (IOException e) {

// TODO Auto-generated catch block

e.printStackTrace();

}

/*

* Add some 400 bytes to simple.csv. outside of this program...

*/

//following line throw exception.

try {

ByteBuffer = fileinput.getChannel().map(FileChannel.MapMode.READ_ONLY, channel.size(), 400);

} catch (IOException e) {

// TODO Auto-generated catch block

e.printStackTrace();

}

So in my code I'm trying to reread the additional data that has been added but its not working, I know the prob is channel.size(), but I'm not able to rectify it.

解决方案

channel.size() is always the current end of file. You are attempting to map 400 bytes past it. It isn't there. You need something like:

ByteBuffer = fileinput.getChannel().map(FileChannel.MapMode.READ_ONLY, channel.size()-400, 400);

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值