1. Understanding byte[] in Text and Binary Data
In Java, you can convert a byte array to a String for text or character data using new String(bytes, StandardCharsets.UTF_8)
. For byte arrays containing binary data, such as images, it’s best to convert them into a Base64 encoded string for safe handling.
// String to byte[]byte[] bytes = "hello".getBytes(StandardCharsets.UTF_8);// byte[] to StringString s = new String(bytes, StandardCharsets.UTF_8);
2. Converting byte[] to String (Text Data)
Here’s a simple example of converting a string to a byte array and then back to a string. A common mistake is using bytes.toString()
, which only returns the object's memory address, not the actual string.
String str = "This is raw text!";byte[] bytes = str.getBytes(StandardCharsets.UTF_8);String s = new String(bytes, StandardCharsets.UTF_8);
3. Converting byte[] to String (Binary Data)
This example shows how to convert an image file into a byte array, then encode it as a Base64 string, and finally decode it back to a byte array.
Path path = Paths.get("/path/to/your/image.png");byte[] bytes = Files.readAllBytes(path);String s = Base64.getEncoder().encodeToString(bytes);byte[] decode = Base64.getDecoder().decode(s);Files.write(Paths.get("/path/to/your/new_image.png"), decode);
4. Download Source Code
To access the complete source code, you can clone our GitHub repository:
$ git clone https://github.com/jimninomics/core-java$ cd java-string
5. References