java - 为什么java nio只能写字节?

标签 java nio

java nio真的只能写字节吗?例如:

    Path path=FileSystems.getDefault().getPath("\(a path)")
    Files.write(path, "test string".getBytes())

我无法仅将字符串传递给 Files.write 的第二个参数。 如果是这样的话,那为什么只能写字节呢?

最佳答案

另一种方法,Files.write(Path,Iterable,Charset,OpenOption...) ,可用于直接写入 CharSequence(StringCharSequence)。

Write lines of text to a file. Each line is a char sequence and is written to the file in sequence with each line terminated by the platform's line separator, as defined by the system property line.separator. Characters are encoded into bytes using the specified charset.

The options parameter specifies how the file is created or opened. If no options are present then this method works as if the CREATE, TRUNCATE_EXISTING, and WRITE options are present. In other words, it opens the file for writing, creating the file if it doesn't exist, or initially truncating an existing regular-file to a size of 0. The method ensures that the file is closed when all lines have been written (or an I/O error or other runtime exception is thrown). If an I/O error occurs then it may do so after the file has been created or truncated, or after some bytes have been written to the file.

Java 8 添加了不需要 Charset 的重载,并使用 UTF-8 作为默认值。

Java 11 添加了另一个方法:Files.writeString(Path,CharSequence,Charset,OpenOption...) .

Write a CharSequence to a file. Characters are encoded into bytes using the specified charset.

All characters are written as they are, including the line separators in the char sequence. No extra characters are added.

The options parameter specifies how the file is created or opened. If no options are present then this method works as if the CREATE, TRUNCATE_EXISTING, and WRITE options are present. In other words, it opens the file for writing, creating the file if it doesn't exist, or initially truncating an existing regular-file to a size of 0.

此方法还有一个不需要 Charset 的重载,再次使用 UTF-8 作为默认值。

然而,在幕后,CharSequence 被转换为字节,就像问题评论中提到的 Scary Wombat 和 yshavit 一样。这些方法的文档甚至明确说明了这一点:

Characters are encoded into bytes using the specified charset.

关于java - 为什么java nio只能写字节?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53255086/

相关文章:

java - 如何自动选择JTable中最后插入的行?

java - Eclipse: 正在调试...然后似乎停在了一个while循环中,没有调试以下代码,为什么?

java - 在 Java 中使用 ByteBuffer 处理交错读/写的最佳方法是什么?

Java I/O 与带有 Linux NPTL 的 Java 新 I/O (NIO)

java - 输入流到选择器的 channel

java - 有没有办法让两个mappedBy ="something"?

java - JOptionPane.showInputDialog 的用户输入验证

java - 如何仅对某些事物使用 Graphics2D g.scale() 而对其他事物不使用?

java - Java 的 NIO2 API 是否可以替代用 NIO 编写单线程多路复用服务器?

java - 如何将文件移动到非空目录?