I want to test MappedByteBuffer‘s READ_WRITE mode. But I get an exception:
Exception in thread "main" java.nio.channels.NonWritableChannelException
at sun.nio.ch.FileChannelImpl.map(FileChannelImpl.java:755)
at test.main(test.java:13)
I have no idea have to fix it.
Thanks in advance.
now I fix the program and there is no exception. But the system returns a sequence of Garbage characters, but in fact there is just a string “asdfghjkl” in the file in.txt . I guess may be the coding scheme cause this problem, but i do not know how to verify it and fix it.
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();
}
};
FileInputStreamis for reading only and you are usingFileChannel.MapMode.READ_WRITE. It should beREADforFileInputStream. UseRandomAccessFile raf = new RandomAccessFile(f, "rw");forREAD_WRITEmap.EDIT:
The character in your file is probably 8 bit, and java uses 16 bit characters. Hence the getChar will read two bytes instead of single byte.
Use
get()method and cast it tocharto get your desired character:Alternatively, since the file is probably US-ASCII based, you can use
CharsetDecoderto obtain aCharBuffer, for instance:will give you desired results as well.