This post originated from an RSS feed registered with Java Buzz
by Javin Paul.
Original Post: How to Convert Byte array to String in Java with Example
Feed Title: Java67
Feed URL: http://www.java67.com/feeds/posts/default?alt=rss
Feed Description: Java and technology tutorials, tips, questions for all programmers.
There are multiple ways to convert a byte array to String in Java but most straight forward way is to use the String constructor which accepts a byte array i.e. new String(byte []) , but key thing to remember is character encoding. Since bytes are binary data but String is character data, its very important to know the original character encoding of the text from which byte array has created. If you use a different character encoding, you will not get the original String back. For example, if you have read that byte array from a file which was encoded in "ISO-8859-1" and you have not provided any character encoding while converting byte array to String using new String() constructor then its not guaranteed that you will get the same text back? Why? because new String() by default uses platform's default encoding (e.g. Linux machine where your JVM is running), which could be different than "ISO-8859-1". If its different you may see some garbage characters or even different characters changing the meaning of text completely and I am not saying this by reading few books, but I have faced this issue in one of my project where we are reading data from database which contains some french characters. In the absent of any specified coding, our platform was defaulted on something which is not able to convert all those special character properly, I don't remember exact encoding. That issue was solved by providing "UTF-8" as character encoding while converting byte array to String. Yes, there is another overloaded constructor in String class which accepts character encoding i.e. new String(byte[], "character encoding").