Learn to convert byte[] array to String and convert String to byte[] array in Java with examples. Conversion between byte array and string may be used in many cases including IO operations, generating secure hashes etc.
1. From byte[] to String 1.1. Using String ConstructorUntil it is absolute necessary, DO NOT convert between string and byte array. They both represent different data; and are there to serve specific purposes i.e. strings are for text, byte[] is for binary data.
To convert a byte array to String
, you can use String
class constructor with byte[]
as the constructor argument.
byte[] bytes = "hello world".getBytes();
String s = new String(bytes);
1.2. Using Base64
Since Java 8, we have Base64 class available. As you might be aware that Base64 is a way to encode binary data, while UTF-8 and UTF-16 are ways to encode Unicode text data. So if you need to encode arbitrary binary data as text, Base64 is the way to go.
byte[] bytes = "hello world".getBytes();
String s = Base64.getEncoder().encodeToString(bytes);
2. From String to byte[] 2.1. Using String.getBytes()
To convert from string to byte array, use String.getBytes() method. Please note that this method uses the platform’s default charset.
String string = "howtodoinjava.com";
byte[] bytes = string.getBytes();
2.2. Using Base64
The Base64.getDecoder().decode() method converts a string to a byte array.
String string = "howtodoinjava.com";
byte[] bytes = Base64.getDecoder().decode(string);
3. Summary
We should focus on the input data type when converting between byte[] array and String in Java.
Drop me your questions in the comments section.
Happy Learning !!
RetroSearch is an open source project built by @garambo | Open a GitHub Issue
Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo
HTML:
3.2
| Encoding:
UTF-8
| Version:
0.7.4