This question is asking specifically why I am getting nulls from this encoding and is not a general question about how to convert a string to an array of bytes.
My actual use-case involves my input being a array of chars which I want to write to disk as an array of encoded bytes.
Why is it that when I try to encode a string in this way, the result has trailing nulls?
String someInput = "///server///server///server///";
char[] chars = someInput.toCharArray();
Charset encoding = StandardCharsets.UTF_8;
CharBuffer buf = CharBuffer.wrap(chars);
for (byte b : encoding.newEncoder().encode(buf).array())
System.out.println("-> " + new Character((char)b));
The output is the following. Note that in the result example I have replaced the nulls with the '�' Unicode character for better visibility.
-> /
-> /
-> /
-> s
-> e
-> r
-> v
-> e
-> r
-> /
-> /
-> /
-> s
-> e
-> r
-> v
-> e
-> r
-> /
-> /
-> /
-> s
-> e
-> r
-> v
-> e
-> r
-> /
-> /
-> /
-> �
-> �
-> �