java实现base64消除行尾换行符
时间: 2024-04-09 09:25:35 浏览: 14
在Java中,可以使用Base64类来实现Base64编码和解码操作。要消除Base64编码后的行尾换行符,可以使用Base64.Encoder类的withoutPadding()方法。
以下是一个示例代码:
```java
import java.util.Base64;
public class Base64Example {
public static void main(String[] args) {
String originalString = "Hello, World!";
// 编码
String encodedString = Base64.getEncoder().encodeToString(originalString.getBytes());
System.out.println("Encoded string: " + encodedString);
// 解码
byte[] decodedBytes = Base64.getDecoder().decode(encodedString);
String decodedString = new String(decodedBytes);
System.out.println("Decoded string: " + decodedString);
// 编码并消除行尾换行符
String encodedStringWithoutPadding = Base64.getEncoder().withoutPadding().encodeToString(originalString.getBytes());
System.out.println("Encoded string without padding: " + encodedStringWithoutPadding);
}
}
```
输出结果:
```
Encoded string: SGVsbG8sIFdvcmxkIQ==
Decoded string: Hello, World!
Encoded string without padding: SGVsbG8sIFdvcmxkIQ
```
在上面的示例中,我们首先将原始字符串进行Base64编码,并打印出编码后的字符串。然后,我们将编码后的字符串进行解码,并打印出解码后的字符串。最后,我们使用withoutPadding()方法对原始字符串进行编码,并消除了行尾换行符。