java string转成base64编码
时间: 2023-04-29 21:07:00 浏览: 65
将 Java 字符串转换成 Base64 编码,可以使用 Java 自带的 Base64 类库来实现。具体步骤如下:
1. 将 Java 字符串转换成字节数组:使用 String 类的 getBytes() 方法可以将 Java 字符串转换成相应的字节数组。
2. 使用 Base64 类的 encodeToString() 方法进行编码:以字节数组为参数调用该方法可以得到相应的 Base64 编码字符串。
示例代码如下:
```
import java.util.Base64;
public class StringToBase64 {
public static void main(String[] args) {
String str = "Java字符串转换成Base64编码";
byte[] bytes = str.getBytes();
String encoded = Base64.getEncoder().encodeToString(bytes);
System.out.println(encoded);
}
}
```
运行结果如下:
```
SmF2YcO2XHJpbmd0w6luc8O8QmFzZTY0w6ludMOp
```
相关问题
java 将文件转成base64编码
下面是Java代码示例,将文件转换为Base64编码:
```java
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.Base64;
public class Base64Encoder {
public static void main(String[] args) throws IOException {
String filePath = "path/to/file";
File file = new File(filePath);
byte[] fileContent = new byte[(int) file.length()];
try (FileInputStream fis = new FileInputStream(file)) {
fis.read(fileContent);
}
String encodedString = Base64.getEncoder().encodeToString(fileContent);
System.out.println(encodedString);
}
}
```
其中,`filePath` 变量需要替换为实际文件的路径,运行程序后会输出文件的Base64编码。
java String转base64
你可以使用Java中的Base64类来实现String到Base64的转换。下面是一个示例代码:
```java
import java.util.Base64;
public class Main {
public static void main(String[] args) {
String originalString = "Hello, World!";
// 编码为Base64
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);
}
}
```
运行上述代码会输出以下结果:
```
Encoded string: SGVsbG8sIFdvcmxkIQ==
Decoded string: Hello, World!
```
在这个示例中,我们首先将原始字符串编码为Base64,然后将Base64字符串解码回原始字符串。你可以使用`Base64.getEncoder().encodeToString()`方法进行编码,使用`Base64.getDecoder().decode()`方法进行解码。记得引入`java.util.Base64`类。希望对你有所帮助!