问题描述
我使用MemoryMapped缓冲区来读取文件。最初我得到的通道大小和使用相同的大小Im映射文件在内存上,这里的初始位置是0,因为我想从头开始映射文件现在另外400KB的数据被添加到该文件,现在我想映射单独的400kb,但是我的代码中的错误,我不能弄清楚,我得到这个
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
这里是我的代码
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();
}
在我的代码中,我试图重新读取已经添加了但它不工作,我知道的概率是channel.size(),但我不能纠正它。
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()
文件结束。您正在尝试映射400字节。它不在那里。你需要类似的东西:
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);
这篇关于使用NIO(Java)在EOF之后重新读取文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!