Skip to main content
Stack Overflow
  1. About
  2. For Teams

You are not logged in. Your edit will be placed in a queue until it is peer reviewed.

We welcome edits that make the post easier to understand and more valuable for readers. Because community members review edits, please try to make the post substantially better than how you found it, for example, by fixing grammar or adding additional resources and hyperlinks.

Required fields*

Required fields*

How to Encode ascent character into UTF-8 without losing its representation?

Method:

public static void test() throws IOException {
 String input = "ABCÉ Ôpqr"; // charsetName = ISO-8859-1
 
 String utf8String = new String(StandardCharsets.UTF_8.encode(input).array());
 }

Required Output:

Output : "ABCÉ Ôpqr" Encoding : UTF-8

I wanted to convert String "ABCÉ Ôpqr" into its UTF-8 encoding without loosing its representation.

Current Output:

Output : "ABC� �pqr"

Answer*

Draft saved
Draft discarded
Cancel
7
  • But in what way would that be useful if input.codePoints() == decoded.codePoints()? Commented Jun 5, 2024 at 22:16
  • @g00se You can't store UTF-8 bytes into a UTF-16 String. The only way for the OP to get their required output (which is the same as the input) using String is to decode the encoded bytes back to UTF-16 using the same Charset that created the bytes. Otherwise, they will have to set their terminal to UTF-8 and output the bytes as-is without going back to a String at all. Commented Jun 5, 2024 at 22:51
  • That doesn't answer my question, which was, to slightly rephrase it: how is the code you just posted useful? Commented Jun 5, 2024 at 22:56
  • @g00se it is useful if the encoded bytes are used for other purposes before decoded, like if they are transmitted or saved somewhere. Commented Jun 5, 2024 at 23:18
  • 1
    What's almost certainly going on is that the string is being viewed on something that doesn't support the encoding used. Code's not really going to help. Not at this stage at least. At this point, we seem to be a lot more interested in this than the OP Commented Jun 5, 2024 at 23:48

lang-java

AltStyle によって変換されたページ (->オリジナル) /