在 Java 中将字符串转换为字节数组、将字节数组转换为字符串

今天我们将学习如何在Java中将字节数转换为字节数,我们还将学习如何在Java中将字节数转换为字节数。

字符串到 byte array

我们可以使用 String 类 getBytes() 方法将字节编码成一个字节序列,使用平台的默认图表。 这种方法是过载的,我们也可以通过 Charset 作为论点。

 1package com.journaldev.util;
 2
 3import java.util.Arrays;
 4
 5public class StringToByteArray {
 6
 7    public static void main(String[] args) {
 8    	String str = "PANKAJ";
 9    	byte[] byteArr = str.getBytes();
10    	// print the byte[] elements
11    	System.out.println("String to byte array: " + Arrays.toString(byteArr));
12    }
13}

Below image shows the output when we run the above program. java string to byte array, string to byte array in java We can also get the byte array using the below code.

1byte[] byteArr = str.getBytes("UTF-8");

但是,如果我们提供 Charset 名称,那么我们将不得不点击UnsupportedEncodingException 例外或扔掉它。

1byte[] byteArr = str.getBytes(StandardCharsets.UTF_8);

这就是在java中将 String 转换为字节数组的所有不同的方法。

Java 字节 Array 到 String

让我们来看看一个简单的程序,展示如何在Java中将字节数组转换为字符串。

 1package com.journaldev.util;
 2
 3public class ByteArrayToString {
 4
 5    public static void main(String[] args) {
 6    	byte[] byteArray = { 'P', 'A', 'N', 'K', 'A', 'J' };
 7    	byte[] byteArray1 = { 80, 65, 78, 75, 65, 74 };
 8
 9    	String str = new String(byteArray);
10    	String str1 = new String(byteArray1);
11
12    	System.out.println(str);
13    	System.out.println(str1);
14    }
15}

Below image shows the output produced by the above program. byte array to string in java, convert byte array to string Did you notice that I am providing char while creating the byte array? It works because of autoboxing and char 'P' is being converted to 80 in the byte array. That's why the output is the same for both the byte array to string conversion. String also has a constructor where we can provide byte array and Charset as an argument. So below code can also be used to convert byte array to String in Java.

1String str = new String(byteArray, StandardCharsets.UTF_8);

String 类还具有将字节数组的子集转换为 String 的方法。

1byte[] byteArray1 = { 80, 65, 78, 75, 65, 74 };
2String str = new String(byteArray1, 0, 3, StandardCharsets.UTF_8);

上面的代码是完美的,而str值将是PAN

您可以从我们的 GitHub 存储库中查阅更多数组示例。

引用: getBytes API Doc

Published At
Categories with 技术
Tagged with
comments powered by Disqus