Java Byte Array to String
December 15, 2022
On this page, we will learn to convert byte[]
to String
in our Java application. We can convert byte[]
to String
using String
constructors. The String
provides constructors for this purpose using bytes, offset, length and charset parameters.
1. Using bytes
Find theString
constructor from Java doc.
public String(byte[] bytes)
Example :
byte[] bytes = "Hello World!".getBytes(); String s = new String(bytes); System.out.println(s);
Hello World!
2. Using bytes, offset and length
Find the String constructor using bytes, offset and length.public String(byte[] bytes, int offset, int length)
bytes : The bytes to be decoded into characters.
offset : The index of the first byte to decode.
length : The number of bytes to decode.
Example :
byte[] bytes = "My name is Neo.".getBytes(); String s = new String(bytes, 3, 12); System.out.println(s);
name is Neo.
3. Using bytes, offset, length and charsetName
Find the String constructor using bytes, offset, length and charsetName.public String(byte[] bytes, int offset, int length, String charsetName)
charsetName : The name of a supported charset.
Throws
The method can throw
UnsupportedEncodingException
and IndexOutOfBoundsException
.
Example :
We can use standard charsets such as US-ASCII, ISO-8859-1, UTF-8, UTF-16BE, UTF-16LE and UTF-16 .
Example :
String s = new String(bytes, 3, 12, "US-ASCII");
4. Using bytes, offset, length and charset
Find the String constructor using bytes, offset, length and charset.public String(byte[] bytes, int offset, int length, Charset charset)
charset : The
Charset
to be used to decode the byte.
Example
String s = new String(bytes, 3, 12, StandardCharsets.US_ASCII);
5. Using bytes and charsetName
Find the String constructor using bytes and charsetName.String(byte[] bytes, String charsetName)
Example :
String s = new String(bytes, "UTF-8");
6. Using bytes and charset
Find the String constructor using bytes and charset.String(byte[] bytes, Charset charset)
Example :
String s = new String(bytes, StandardCharsets.UTF_8);