java语音file转base64
时间: 2023-12-06 19:35:48 浏览: 44
以下是Java语言中将文件转换为Base64编码的示例代码:
```java
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.Base64;
public class FileToBase64 {
public static void main(String[] args) {
String filePath = "C:\\example\\example.jpg"; // 文件路径
File file = new File(filePath);
try (FileInputStream fis = new FileInputStream(file)) {
byte[] bytes = new byte[(int) file.length()];
fis.read(bytes);
String base64Str = Base64.getEncoder().encodeToString(bytes);
System.out.println(base64Str);
} catch (IOException e) {
e.printStackTrace();
}
}
}
```
在上述代码中,我们首先定义了一个文件路径,然后创建了一个File对象,接着使用FileInputStream读取文件内容,并将其存储在一个byte数组中。最后,我们使用Base64.getEncoder()方法将byte数组转换为Base64编码的字符串,并将其打印输出。
相关推荐
![java](https://img-home.csdnimg.cn/images/20210720083646.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)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)