SoFunction
Updated on 2025-04-06

Java implements mutual conversion between strings and byte arrays

1. Convert string to byte array

In Java, strings are composed of sequences of characters, and characters are stored in Unicode encoding in memory. To convert a string to a byte array, we need to specify a character encoding (Charset) in order to encode the character sequence into a byte sequence.

1.1 Use the getBytes() method

In JavaStringThe class provides agetBytes()Method, convert strings into byte arrays. This method has multiple overloaded versions, the most commonly used versions without parameters and versions encoded with specified characters.

1.1.1 getBytes() without parameters

String str = "Hello, World!";
byte[] byteArray = ();

In this example, the getBytes() method converts the string to a byte array using the platform's default character encoding (usually UTF-8). It should be noted that the default encodings for different platforms may be different, so this approach may lead to cross-platform compatibility issues.

1.1.2 GetBytes() with specified character encoding

To avoid the problems caused by platform default encoding, we can explicitly specify character encoding:

String str = "Hello, World!";
byte[] byteArray = (StandardCharsets.UTF_8);

In this example, we used StandardCharsets.UTF_8 to specify the UTF-8 encoding. StandardCharsets is a tool class introduced in Java 7 that provides common character encoding constants.

1.2 Using the Charset class

In addition to using StandardCharsets, we can also use the Charset class to specify character encoding:

import ;

String str = "Hello, World!";
Charset charset = ("UTF-8");
byte[] byteArray = (charset);

This method and useStandardCharsetsSimilar, but provides greater flexibility as we can specify character encoding dynamically.

2. Convert byte array to string

The process of converting a byte array back to a string is the opposite of the above. We need to decode the byte array into a sequence of characters using the same character encoding.

2.1 Using String constructor

The String class in Java provides multiple constructors that can convert byte arrays into strings. The most commonly used constructors that use specified character encoding.

2.1.1 Constructors using specified character encoding

byte[] byteArray = {72, 101, 108, 108, 111, 44, 32, 87, 111, 114, 108, 100, 33};
String str = new String(byteArray, StandardCharsets.UTF_8);

In this example, we useStandardCharsets.UTF_8To specify UTF-8 encoding. In this way, the byte array will be decoded into the corresponding string.

2.1.2 Using the Charset class

Similarly, we can useCharsetClass to specify character encoding:

import ;

byte[] byteArray = {72, 101, 108, 108, 111, 44, 32, 87, 111, 114, 108, 100, 33};
Charset charset = ("UTF-8");
String str = new String(byteArray, charset);

2.2 Using String's valueOf() method

AlthoughStringClass providedvalueOf()method, but it does not directly support conversion from byte array to string. Therefore, we usually use constructors to complete this conversion.

3. Things to note

There are several important things to note when converting strings and byte arrays:

3.1 Consistency of character encoding

When performing conversions, it is necessary to ensure that the encoding and decoding use the same character encoding. If the character encoding used in encoding and decoding is inconsistent, it may lead to garbled code or data corruption.

3.2 Handling exceptions

try {
    byte[] byteArray = ("UTF-8");
    String str = new String(byteArray, "UTF-8");
} catch (UnsupportedEncodingException e) {
    ();
}

3.3 Processing non-text data

If the byte array represents non-text data (such as pictures, audio, etc.), it should not be converted to a string. A string is used to represent text data, and converting non-text data into a string may result in data corruption or unpredictable results.

4. Summary

In Java, the mutual conversion between strings and byte arrays is a common operation. By usinggetBytes()Methods andStringConstructor, we can easily implement this transformation. However, when performing conversions, it is necessary to pay attention to the consistency of character encoding and handle possible exceptions. Also, for non-text data, it should be avoided to convert it to a string.

The above is the detailed content of Java implementing the mutual conversion between strings and byte arrays. For more information about the mutual conversion of Java strings and byte arrays, please pay attention to my other related articles!