MappedByteBuffer有奖问答!

QOUIQWOQ 2003-09-22 01:05:28
下面是有问题的代码,非常简单。但是异常让我很困惑,期望各位伸手相救!
异常是:
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;
}

}
...全文
100 3 打赏 收藏 转发到动态 举报
写回复
用AI写文章
3 条回复
切换为时间正序
请发表友善的回复…
发表回复
QOUIQWOQ 2003-09-22
  • 打赏
  • 举报
回复
我是想改变文件的大小啊,这样能改变文件的大小吗?请指教。
Keepers 2003-09-22
  • 打赏
  • 举报
回复
你要先用long getPointer = rafo.getFilePointer();取得文件的大小
然后再根据这个值调整

rafo= new RandomAccessFile( "aaa.txt", "rw");
long getPointer = rafo.getFilePointer();
rafo.setLength(getPointer);
fc= rafo.getChannel();
MappedByteBuffer mbb = fc.map( FileChannel.MapMode.READ_WRITE, 0L , fc.size());
return mbb;
QOUIQWOQ 2003-09-22
  • 打赏
  • 举报
回复
自己顶~~

62,612

社区成员

发帖
与我相关
我的任务
社区描述
Java 2 Standard Edition
社区管理员
  • Java SE
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧