java nio真的只能写字节吗?例如:
Path path=FileSystems.getDefault().getPath("\(a path)")
Files.write(path, "test string".getBytes())
我无法仅将字符串传递给 Files.write 的第二个参数。 如果是这样的话,那为什么只能写字节呢?
最佳答案
另一种方法,Files.write(Path,Iterable,Charset,OpenOption...)
,可用于直接写入 CharSequence
(String
是 CharSequence
)。
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 of0
. 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 of0
.
此方法还有一个不需要 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/