user911625
user911625

Reputation:

OutputStreamWriter constructor: how does the encoding work?

I am not a Java developer. I just have to understand what this constructor is doing:

x = new OutputStreamWriter(OutputStream output, "UTF-8") 
x.write(some string)

I've simplified the code a bit hopefully to highlight my essential question.

The docs says:

Characters written to it are encoded into bytes using a specified charset.

Does this mean that the string in x is now encoded into UTF-8? Does this do conversion? If the string passed to .write is say an ISO-8859-1 string will this be converted? How will it know?

Upvotes: 0

Views: 826

Answers (1)

Jon Skeet
Jon Skeet

Reputation: 1500923

Does this mean that the string in x is now encoded into UTF-8?

No. It means that when the writer receives a string (which is always effectively in UTF-16) it is encoded into bytes using the specified encoding, and then written to the underlying OutputStream.

The important point to note is that an OutputStream is asked to write bytes, whereas a Writer is asked to write text. The encoding specifies the conversion applied to the text data in order to get binary data, basically.

Upvotes: 2

Related Questions