How does Java use the getBytes() function of the String class to convert a string into a byte array according to the specified character set
In Java programming, sometimes we need to convert a string into a byte array according to the specified character set. Byte array. Java provides the getBytes() function of the String class to meet this requirement. This article will introduce how to use the getBytes() function of the String class to implement this function and provide code examples.
The getBytes() function of the String class has two overloaded forms, one is getBytes() and the other is getBytes(String charsetName). Let's look at the first form first.
The getBytes() function will use the default character set to convert a string into a byte array. The default character set depends on the operating system's default character set.
Code example:
String str = "Hello, World!"; byte[] bytes = str.getBytes(); for (byte b : bytes) { System.out.print(b + " "); }
Output result:
72 101 108 108 111 44 32 87 111 114 108 100 33
In the above example, We convert the string "Hello, World!" into a byte array bytes, and use a for loop to traverse the byte array and print the value of each byte.
The getBytes(String charsetName) function can convert the string into the specified character set Character set converted to byte array. The character set is specified by the character encoding (such as UTF-8, GBK, etc.).
Code example:
String str = "你好,世界!"; byte[] bytes = str.getBytes("UTF-8"); for (byte b : bytes) { System.out.print(b + " "); }
Output result:
-28 -67 -96 -27 -91 -67 -17 -68 -112 -27 -91 -67 - 17 -68 -65 -17 -68 -78 -17 -68 -109 -17 -68 -78 -17 -68 -73 -17 -68 -107
In the above example, we will The string "Hello, world!" is converted into a byte array bytes according to UTF-8 encoding, and a for loop is used to traverse the byte array to print the value of each byte.
It should be noted that the getBytes(String charsetName) function may throw an UnsupportedEncodingException exception, so exception handling must be performed when using it.
Summary:
This article introduces how to use the getBytes() function of the String class to convert a string into a byte array according to the specified character set. By changing the overloaded form of the function and passing in the character encoding, we can flexibly convert strings and byte arrays. This is very useful in scenarios such as processing network data and file reading and writing.
I hope this article will be helpful to you, and I wish you good results in Java programming!
The above is the detailed content of How does Java use the getBytes() function of the String class to convert a string into a byte array according to the specified character set?. For more information, please follow other related articles on the PHP Chinese website!