Java NIO issue on CharBuffer

I am using the following code to read a subsequence from a file.

FileChannel channel = new RandomAccessFile("abc.txt", "r").getChannel();
ByteBuffer buffer = channel.map(FileChannel.MapMode.READ_ONLY, 0, channel.size());
CharBuffer cbuf = buffer.asCharBuffer();

String str = cbuf.subSequence(0, 1).toString();
System.out.println("str = " + str);

However, this gives the output "str =?" Can someone help me why this is happening and how to solve it? Sorry, I'm new to NIO.

Extra thing when I add System.out.println (buffer); it gives the result "java.nio.DirectByteBufferR [pos = 0 lim = 16 cap = 16]".

System.out.println ((char) buffer.get (0)) gives the correct 1st character output.

+5
source share
1 answer

Try this method, you have a problem with the encoding:

    FileChannel channel = new RandomAccessFile("/home/alain/Bureau/clair.txt", "r").getChannel();
    ByteBuffer buffer = channel.map(FileChannel.MapMode.READ_ONLY, 0, channel.size());
    Charset chars = Charset.forName("ISO-8859-1");
    CharBuffer cbuf = chars.decode(buffer);
    String str = cbuf.subSequence(0, 10).toString();
    System.out.println("str = " + str);
+3
source

All Articles