Recently I've started learning about java.nio. And I have an example in my textbook how to read text file with SeekableByteChannel:
int count;
Path path;
try {
path = Paths.get(System.getProperty("user.home") + "/desktop/text.txt");
} catch (InvalidPathException e) {
out.println(e.getMessage());
return;
}
try (SeekableByteChannel channel = Files.newByteChannel(path)) {
ByteBuffer buffer = ByteBuffer.allocate(128);
do {
count = channel.read(buffer);
if (count != -1) {
buffer.rewind();
for (int i = 0; i < count; i++)
out.print((char) buffer.get());
}
} while (count != -1);
} catch (IOException e) {
out.println("File not found!!!");
}
out.flush();
So I've made a text file with english and russian words in it using an ANSI encoding. And this is what I get:
Method buffer.get() returns byte value and russian characters start from somewhere 1000. So I've changed encoding to UTF-8 and used another method:
for (int i = 0; i < count; i += 2)
out.print(buffer.getChar()); //reads 2 bytes and converts them to char
But this gives me a line of question marks.
So does anyone know how to properly read russian text using SeekableByteChannel?