Reader and Writer classes are character oriented stream classes. These can be used to read and convert Unicode characters.
Conversion
Following example will showcase conversion of a Unicode String to UTF8 byte[] and UTF8 byte[] to Unicode byte[] using Reader and Writer classes.
Example
Open Compiler
importjava.io.ByteArrayInputStream;importjava.io.ByteArrayOutputStream;importjava.io.IOException;importjava.io.InputStream;importjava.io.InputStreamReader;importjava.io.OutputStreamWriter;importjava.io.Reader;importjava.io.Writer;importjava.nio.charset.Charset;importjava.text.ParseException;publicclassI18NTester{publicstaticvoidmain(String[] args)throwsParseException,IOException{String input ="This is a sample text";InputStream inputStream =newByteArrayInputStream(input.getBytes());//get the UTF-8 dataReader reader =newInputStreamReader(inputStream,Charset.forName("UTF-8"));//convert UTF-8 to Unicodeint data = reader.read();while(data !=-1){char theChar =(char) data;System.out.print(theChar);
data = reader.read();}
reader.close();System.out.println();//Convert Unicode to UTF-8 BytesByteArrayOutputStream outputStream =newByteArrayOutputStream();Writer writer =newOutputStreamWriter(outputStream,Charset.forName("UTF-8"));
writer.write(input);
writer.close();String out =newString(outputStream.toByteArray());System.out.println(out);}}
Output
It will print the following result.
This is a sample text
This is a sample text
Leave a Reply