Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.nio.charset.StandardCharsets;
public class Foo {
public static void main(String[] args) throws IOException {
final char c = 'ñ';
final ByteArrayOutputStream baos = new ByteArrayOutputStream();
final OutputStreamWriter writer = new OutputStreamWriter(baos);
writer.write(c);
writer.close();
final String string = baos.toString("UTF-8");
System.out.printf("string: %s%n", string);
System.out.printf("length: %s%n", string.length());
System.out.printf(" chars: %s%n", string.toCharArray().length);
System.out.printf(" bytes: %s%n", baos.toByteArray().length);
System.out.printf(" bytes: %s%n", string.getBytes(StandardCharsets.UTF_8).length);
}
}
string: ñ
length: 1
chars: 1
bytes: 2
bytes: 2
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment