Java中的常用编码函数
发布时间:2023-06-02 23:06:47
Java中的常用编码函数主要是用于字符串与字节之间的转换,包括将字符串编码为字节数组、将字节数组解码为字符串、进行URL编码和解码、Base64编码和解码等。以下是Java中常用的编码函数介绍。
1. String.getBytes():将字符串转换为字节数组
该方法将字符串转换为字节数组,可以指定编码方式。例如:
String str = "Hello World!";
byte[] bytes = str.getBytes("UTF-8");
2. new String(bytes, charsetName):将字节数组转换为字符串
该方法将字节数组转换为字符串,需要指定字节数组的编码方式。例如:
byte[] bytes = {72, 101, 108, 108, 111, 32, 87, 111, 114, 108, 100, 33};
String str = new String(bytes, "UTF-8");
3. URLEncoder.encode(String s, String enc):进行URL编码
该方法将字符串进行URL编码,可以指定编码方式。例如:
String str = "Hello World!"; String encodedStr = URLEncoder.encode(str, "UTF-8");
4. URLDecoder.decode(String s, String enc):进行URL解码
该方法对进行URL编码的字符串进行URL解码,需要指定编码方式。例如:
String encodedStr = "Hello%20World%21"; String decodedStr = URLDecoder.decode(encodedStr, "UTF-8");
5. Base64.getEncoder().encodeToString(byte[] src):进行Base64编码
该方法将字节数组进行Base64编码,并返回编码后的字符串。例如:
String str = "Hello World!";
byte[] bytes = str.getBytes("UTF-8");
String encodedStr = Base64.getEncoder().encodeToString(bytes);
6. Base64.getDecoder().decode(String src):进行Base64解码
该方法将进行Base64编码的字符串进行解码,返回解码后的字节数组。例如:
String encodedStr = "SGVsbG8gV29ybGQh"; byte[] bytes = Base64.getDecoder().decode(encodedStr); String str = new String(bytes, "UTF-8");
以上是Java中常用的编码函数介绍,通过使用这些函数,可以方便地进行字符串与字节之间的转换以及进行URL编码和解码、Base64编码和解码等操作。
