SourceEngine
SourceEngine

Reputation: 31

Why can java nio only write bytes?

Is it true that java nio can only write bytes? For instance:

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

I cannot pass only a string to the second parameter of Files.write. If this is the case, then why is it that only bytes can be written?

Upvotes: 0

Views: 216

Answers (1)

Slaw
Slaw

Reputation: 46181

Another method, Files.write(Path,Iterable,Charset,OpenOption...), can be used to write CharSequences directly (a String is a 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 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 added an overload that doesn't require a Charset and uses UTF-8 as a default.

Java 11 added another method: 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.

This method also has an overload that doesn't require a Charset, using UTF-8 as a default again.

Under the hood, however, the CharSequences are converted to bytes just like Scary Wombat and yshavit mention in the question comments. The documentation of these methods even make this explicit:

Characters are encoded into bytes using the specified charset.

Upvotes: 3

Related Questions