我想測試MappedByteBuffer
的READ_WRITE模式。但我得到一個例外:使用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();
}
};
@Charles Menguy感謝格式。你使用反引號來標記代碼嗎? –
感謝您的幫助。現在我有另一個問題,請再次看到我的問題,我已經編輯它 – city
@city回答更新。 –