Java Reference
In-Depth Information
helloworld.sjis.txt");
InputStreamReader reader = null;
StringBuilder sb = new StringBuilder();
if (is != null){
reader = new InputStreamReader(is,
Charset.forName("SJIS"));
int ch = reader.read();
while(ch != -1) {
sb.append((char)ch);
ch = reader.read();
}
reader.close();
}
return sb.toString();
}
Similarly, you can use an
OutputStreamWriter
to write text to a byte stream.
The following code writes a string to a UTF-8 encoded byte stream:
public void writeStream(String text) throws IOException {
OutputStreamWriter writer = null;
FileOutputStream fos = new
FileOutputStream("helloworld.utf8.txt");
writer = new OutputStreamWriter(fos,
Charset.forName("UTF-8"));
writer.write(text);
writer.close();
}
Solution 2
Use
java.nio.charset.CharsetEncoder
and
java.nio.charset.CharsetDecoder
to convert Unicode character buffers to
and from byte buffers. Retrieve an encoder or decoder from a
charset
instance with
the
newEncoder()
or
newDecoder()
method. Then use the encoder's
en-
code()
method to create byte buffers. Use the decoder's
decode()
method to cre-
ate character buffers. The following code from the