下面这段代码为什么会有异常呢?异常是:
BufferOverflowException - 如果此缓冲区的当前位置不小于界限 
我是向文件中写入,和当前位置及界限有什么关系啊?

import java.io.IOException;
import java.io.RandomAccessFile;
import java.nio.IntBuffer;
import java.nio.channels.FileChannel;
public class MyTest { private static int numOfInts = 4000000;
public static void test()throws IOException{
FileChannel fc = new RandomAccessFile("D:\\333\\text.txt", "rw").getChannel();
IntBuffer ib = fc.map(FileChannel.MapMode.READ_WRITE, 0, fc.size()).asIntBuffer();
for(int i = 0; i < numOfInts; i++){
ib.put(i);
}
fc.close();
}
public static void main(String[] args){
try{
test();
}catch(IOException e){
throw new RuntimeException();
}
}
}

解决方案 »

  1.   

    import java.io.*;
    public class BufferIn {
    public static void Show() {
    BufferedReader in = null;
    Reader f = null;
    try {
    f = new FileReader("f:\\f.txt");
    in = new BufferedReader(f);
    System.out.println(in.readLine());
    } catch (Exception e) {
    e.printStackTrace();
    } finally {
    try {
    if (in != null)
    in.close();
    } catch (Exception e) {
    // TODO: handle exception
    }
    try {
    if (f != null)
    f.close();
    } catch (Exception e) {
    // TODO: handle exception
    }
    }
    } public static void main(String[] args) {
    Show();
    }
    }
    换一种方法试试。
      

  2.   


    IntBuffer ib = fc.map(FileChannel.MapMode.READ_WRITE, 0, fc.size()).asIntBuffer();D:\\333\\text.txt 这个文件初始大小是多少?是0吗。
    你这里整了一个大小为0的缓冲区,往里面放东西那还不溢出啊。
      

  3.   

    fc.size()的值设为已知的值,如1024
      

  4.   

    映射区域太小,fc.size=0导致//把这句
    IntBuffer ib = fc.map(FileChannel.MapMode.READ_WRITE, 0, fc.size()).asIntBuffer();
    //改成应该就没问题了
    IntBuffer ib = fc.map(FileChannel.MapMode.READ_WRITE, 0, 4*numOfInts).asIntBuffer();