MappedByteBuffer and UTF-8
Hello java ppl,
For some hours now I am experimenting with MappedByteBuffer, and I
have the following issue:
Firstly I write 10 integers, followed by a String encoded in UTF-8.
Next when I try to read it back, but the String is garbage formated.
Here is the (messy)code:
public class MemoryMappingRW {
MappedByteBuffer mbb;
public MemoryMappingRW(String fileName) throws
java.io.FileNotFoundException, java.io.IOException {
File myFile = new File(fileName);
if (myFile.exists()) {
myFile.delete();
}
mbb = new RandomAccessFile(myFile, "rw").getChannel().map(
FileChannel.MapMode.READ_WRITE, 0, 0x8FFFFFF);
}
public static void main(String[] args) throws Exception {
MemoryMappingRW mm = new MemoryMappingRW("test.dat");
System.out.println(System.getProperty("file.encoding"));
for (int i = 0; i < 10; i++) {
mm.mbb.putInt(i);
}
mm.mbb.put(ByteBuffer.wrap("test =E4=EF=EA=E9=EC=E7".getBytes()));
int strLength = Charset.forName("UTF-8").encode("test
=E4=EF=EA=E9=EC=E7").array().length;
mm.mbb.clear();
for (int i = 0; i < 10; i++) {
System.out.print(mm.mbb.getInt() + " ");
}
char[] chArray = new char[strLength];
mm.mbb.asCharBuffer().get(chArray);
String anStr = new String(chArray);
System.out.println("\n" +
Charset.forName("UTF-8").decode(ByteBuffer.wrap(anStr.getBytes())));
}
}
// END
I am running it on Linux and my environment is configured as follows:
LANG=en_US.UTF-8
LC_ALL=en_US.UTF-8
Also by running "cat path_to/test.dat", I can see that the String is
encoded correctly.
Any help would be appreciated
Regards
Yiannis