I'm trying to write some text into a file using a FileChannel. So far everything works fine except for the fact that umlauts are not written correctly.
Path fileChannel = Paths.get("c:/channel.txt");
try (FileChannel channel = FileChannel.open(
fileChannel,
StandardOpenOption.CREATE,
StandardOpenOption.READ,
StandardOpenOption.WRITE)) {
String response = "Würzburg";
channel.write(ByteBuffer.wrap(response.getBytes(StandardCharsets.UTF_8)));
}
In this example, I want to write Würzburg into the file, but when I open it, it contains the following: Würzburg. The file itself is utf-8.
Any suggestions, what could be done?
edit:
Finally, I would like to read out the file again, for example like this:
try (FileChannel channel = FileChannel.open(fileChannel, StandardOpenOption.READ)) {
byte[] buffer = new byte[(int) channel.size()];
ByteBuffer bb = ByteBuffer.wrap(buffer);
channel.read(bb);
String request = new String(buffer, StandardCharsets.UTF_8);
System.out.println(request);
}
However, a comparison of the strings response and request shows that they are not identical.
Running on a Windows machine, Java 17 (IntelliJ configured with adoptium open jdk)