- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
How to convert a String to and fro from UTF8 byte array
Following example will showcase conversion of a Unicode String to UTF8 byte[] and UTF8 byte[] to Unicode byte[] using Reader and Writer classes.
Example
IOTester.java
import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.io.Reader; import java.io.Writer; import java.nio.charset.Charset; import java.text.ParseException; public class I18NTester { public static void main(String[] args) throws ParseException, IOException { String input = "This is a sample text" ; InputStream inputStream = new ByteArrayInputStream(input.getBytes()); //get the UTF-8 data Reader reader = new InputStreamReader(inputStream, Charset.forName("UTF-8")); //convert UTF-8 to Unicode int 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 Bytes ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); Writer writer = new OutputStreamWriter(outputStream, Charset.forName("UTF-8")); writer.write(input); writer.close(); String out = new String(outputStream.toByteArray()); System.out.println(out); } }
Output
It will print the following result. This is a sample text This is a sample text
- Related Articles
- How to convert byte array to string in C#?
- How to convert a byte array to hex string in Java?
- How to convert a byte array to a hex string in Java?
- How to convert hex string to byte Array in Java?
- Java Program to convert byte[] array to String
- Java Program to convert String to byte array
- Convert byte Array to Hex String in Java
- Convert Hex String to byte Array in Java
- How to convert a PDF to byte array in Java?
- Java Program to create Stream from a String/Byte Array
- Convert byte to String in Java
- Java Program to convert byte to string
- Java Program to convert string to byte
- How to convert BLOB to Byte Array in java?
- How to convert Byte Array to Image in java?

Advertisements