MappedByteBuffer有奖问答!
下面是有问题的代码,非常简单。但是异常让我很困惑,期望各位伸手相救!
异常是:
java.io.IOException: 请求的操作无法在使用用户映射区域打开的文件上执行。
位于setLength()这一行。
resize()执行了两次,一次生成4096长的buffer,第二次生成1024长的buffer;就报上面的异常;如果我将两次对调,先生成1024的,再生成4096的就没有问题。我的平台是jdk1.4.1 windows2000。我感觉有资源被锁,但找不到解决的办法。另外,MappedByteBuffer如何动态调整到文件的大小呢?每次生成一个太浪费。
public class TestRandomAccess {
/**
* @param args
*/
public static void main( String args[]) {
resize( 4096, "hello world!");
resize( 1024, "hello world!");
}
/**
* @param l
*/
public static MappedByteBuffer resize( long l, String str) {
RandomAccessFile rafo= null;
FileChannel fc= null;
try {
rafo= new RandomAccessFile( "E:\\test.ram", "rw");
rafo.setLength( l);
fc= rafo.getChannel();
mbb= fc.map( FileChannel.MapMode.READ_WRITE, 0L , fc.size());
return mbb;
}catch ( Exception ex) {
ex.printStackTrace();
}finally {
try {
if ( rafo!= null) rafo.close();
}catch ( Exception ex) {}
try {
if ( fc!= null) fc.close();
}catch ( Exception ex) {}
}
return null;
}
}