使用MappedByteBuffer的READ_Write模式时发生异常

时间:2013-01-10 03:59:56

标签: java

我想测试MappedByteBuffer的READ_WRITE模式。但我得到一个例外:

Exception in thread "main" java.nio.channels.NonWritableChannelException
 at sun.nio.ch.FileChannelImpl.map(FileChannelImpl.java:755)
 at test.main(test.java:13)

我不知道要修理它。 提前谢谢。

现在我修复了程序,没有例外。但系统返回一系列垃圾字符,但实际上文件in.txt中只有一个字符串“asdfghjkl”。我想可能是编码方案导致这个问题,但我不知道如何验证它并修复它。

import java.io.File;
import java.nio.channels.*;
import java.nio.MappedByteBuffer;
import java.io.RandomAccessFile;

class test{
    public static void main(String[] args) throws Exception{

    File f= new File("./in.txt");
    RandomAccessFile in = new RandomAccessFile(f, "rws");
    FileChannel fc = in.getChannel();
    MappedByteBuffer mbb = fc.map(FileChannel.MapMode.READ_WRITE, 0, f.length());

    while(mbb.hasRemaining())
        System.out.print(mbb.getChar());
    fc.close();
    in.close();

    }
};

2 个答案:

答案 0 :(得分:1)

FileInputStream仅供阅读,您使用FileChannel.MapMode.READ_WRITEREAD应为FileInputStream。将RandomAccessFile raf = new RandomAccessFile(f, "rw");用于READ_WRITE地图。

修改 文件中的字符可能是8位,java使用16位字符。因此getChar将读取两个字节而不是单个字节。

使用get()方法并将其投射到char以获得所需的角色:

while(mbb.hasRemaining())
        System.out.print((char)mbb.get());

或者,由于该文件可能是基于US-ASCII的,因此您可以使用CharsetDecoder获取CharBuffer,例如:

import java.io.*;
import java.nio.*;
import java.nio.channels.*;
import java.nio.charset.*;

public class TestFC {
        public static void main(String a[]) throws IOException{
                File f = new File("in.txt");
                try(RandomAccessFile in = new RandomAccessFile(f, "rws"); FileChannel fc = in.getChannel();) {
                        MappedByteBuffer mbb = fc.map(FileChannel.MapMode.READ_WRITE, 0, f.length());

                        Charset charset = Charset.forName("US-ASCII");
                        CharsetDecoder decoder = charset.newDecoder();
                        CharBuffer cb = decoder.decode(mbb);

                        for(int i=0; i<cb.limit();i++) {
                                System.out.print(cb.get(i));
                        }
                }
        }
}

也会给你想要的结果。

答案 1 :(得分:1)

度Acc。致Javadocs:

  

NonWritableChannelException - 如果模式为READ_WRITE或PRIVATE,但此通道未打开以进行读写

     

FileInputStream - 用于读取原始字节流,例如图像数据。

     

RandomAccessFile - 此类的实例支持读取和写入随机访问文件

代替FileInputStream,使用RandomAccessFile