How to force UTF-16 while reading / writing in Java?

I see that you can specify UTF-16 as an encoding through Charset.forName("UTF-16"), and that you can create a new UTF-16 decoder through Charset.forName("UTF-16").newDecoder(), but I see only the ability to specify CharsetDecoderon InputStreamReader.

Like so, how do you specify to use UTF-16 when reading any stream in Java?

+5
source share
1 answer

Input streams deal with raw bytes. When you read directly from the input stream, all you get is raw bytes, where character sets don't matter.

- : ? "" .

"" Readers. ( ) Reader ( ) . :

InputStream is = ...;
Reader reader = new InputStreamReader(is, Charset.forName("UTF-16"));

, reader.read() , . , BufferedReader :

BufferedReader reader = new BufferedReader(new InputStreamReader(is, Charset.forName("UTF-16")));
String line = reader.readLine();
+11

All Articles