如何从字符串提取字符到字节数组?及还原字节数组字符串为字节数组
Hey there! Let's tackle your two questions one by one, since they're related but have distinct nuances:
In Java, converting a string's characters to a byte array all comes down to character encoding—different encodings (like UTF-8, ISO-8859-1) will map characters to different byte sequences, so it's crucial to pick the right one for your use case.
Here's how to do it properly, explicitly specifying the encoding to avoid system-dependent behavior:
import java.nio.charset.StandardCharsets; public class StringToByteArray { public static void main(String[] args) { String inputString = "Your sample string here"; // Using UTF-8 (most common for cross-platform compatibility) byte[] utf8Bytes = inputString.getBytes(StandardCharsets.UTF_8); // Using ISO-8859-1 (for single-byte character sets) byte[] isoBytes = inputString.getBytes(StandardCharsets.ISO_8859_1); } }
Always avoid the no-argument getBytes() method—it uses the system's default encoding, which can vary across environments and lead to inconsistent results.
First, a critical clarification: this string does NOT contain any of the byte array's actual data. It's the output of Java's default toString() method called on a byte[] array. Breaking it down:
[Bindicates the type is a byte array@separates the type from the hash code- The hex string after
@is just the object's hash code—used to distinguish different objects, not store array content
So you can't directly restore the original byte array from this string alone. But here's how to fix the root problem and handle this scenario:
If you generated this string yourself
Stop using byteArray.toString() to persist or share your byte array. Instead, convert it to a format that preserves all data, like Base64 or hexadecimal:
Option 1: Base64 (most compact and widely supported)
import java.util.Base64; public class ByteArrayToBase64 { public static void main(String[] args) { byte[] originalArray = {0x12, 0x34, 0x56, 0x78}; // Convert byte array to Base64 string for storage/sharing String base64String = Base64.getEncoder().encodeToString(originalArray); // Restore byte array from Base64 string byte[] restoredArray = Base64.getDecoder().decode(base64String); } }
Option 2: Hexadecimal (human-readable, slightly longer)
import javax.xml.bind.DatatypeConverter; public class ByteArrayToHex { public static void main(String[] args) { byte[] originalArray = {0x12, 0x34, 0x56, 0x78}; // Convert to hex string String hexString = DatatypeConverter.printHexBinary(originalArray); // Restore from hex string byte[] restoredArray = DatatypeConverter.parseHexBinary(hexString); } }
If someone else provided this string
Unfortunately, you can't recover the original byte array from "[B@42b19e58"—it lacks all the actual array data. You'll need to ask the provider to send you the byte array in a recoverable format (like Base64 or hex) instead of the toString() output.
内容的提问来源于stack exchange,提问作者Himanshu Choudhary

