我正在使用MemoryMap缓冲区来读取文件。最初我正在获取通道大小并使用相同的大小在内存上映射文件,这里的初始位置为 0,因为我想从头开始映射文件。现在又有 400KB 的数据添加到该文件中,现在我想单独映射这 400kb。但是我的代码有问题,我无法弄清楚,我得到了这个
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(),但我无法纠正它。
channel.size()
始终是文件的当前结尾。您正在尝试映射 400 个字节。它不存在。你需要这样的东西:
ByteBuffer = fileinput.getChannel().map(FileChannel.MapMode.READ_ONLY, channel.size()-400, 400);