Верно ли, что java nio может писать только байты? Например:
Path path=FileSystems.getDefault().getPath("\(a path)")
Files.write(path, "test string".getBytes())
Я не могу передать только строку второму параметру Files.write. Если это так, то почему можно записывать только байты?
Байты - это то, что содержат файлы. Все, что выглядит так, будто записывает строки, на самом деле преобразует их в байты и записывает их. nio в основном задумывался как быстрый и эффективный интерфейс, поэтому логично, что у него не было бы этих помощников.




Другой метод, 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
optionsparameter 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
optionsparameter 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.
все может писать только байты