Filechannel不正确编写特殊字符

发布于 2025-01-30 17:10:21 字数 986 浏览 3 评论 0原文

我正在尝试使用Filechannel将一些文本写入文件中。到目前为止,一切正常,除了umlauts未正确编写的事实。

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)));

}

在此示例中,我想将würzburg写入文件,但是当我打开它时,它包含以下内容:wã¼rzburg。该文件本身是UTF-8。

有什么建议,该怎么办?

编辑:

最后,我想再次读取文件,例如这样:

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);

}

但是,对字符串响应的比较和请求表明它们并不相同。

在Windows计算机上运行Java 17(Intellij配置了采用JDK)

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)

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文