algorithm.update(s.getBytes("UTF-8"));将charset name参数替换为StandardCharsets。UTF_8
时间: 2024-03-20 20:42:27 浏览: 25
可以将`algorithm.update(s.getBytes("UTF-8"));`替换为`algorithm.update(s.getBytes(StandardCharsets.UTF_8));`,这样可以使用Java 7中引入的`StandardCharsets`类,使代码更清晰和易读。`StandardCharsets`类是Java 7中添加的,它提供了一些常量,用于表示Java平台支持的字符集。使用这些常量可以避免硬编码字符集名称,使代码更加可读和可维护。因此,修改后的代码如下:
```
private static byte[] md5(String s) {
MessageDigest algorithm;
try {
algorithm = MessageDigest.getInstance("MD5");
algorithm.reset();
algorithm.update(s.getBytes(StandardCharsets.UTF_8));
byte[] messageDigest = algorithm.digest();
return messageDigest;
} catch (Exception e) {
log.error("MD5 Error...{}", e.getMessage());
}
return new byte[0];
}
```
需要注意的是,对于早期版本的Java,如果不能使用`StandardCharsets`类,可以使用`Charset.forName("UTF-8")`替代`StandardCharsets.UTF_8`。
相关推荐
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)