java file base64
时间: 2023-10-14 11:03:36 浏览: 45
以下是Java中对文件进行Base64编解码的示例代码:
```java
import java.io.*;
import java.util.Base64;
public class Base64File {
public static void main(String[] args) throws IOException {
// 读取文件内容
File file = new File("test.txt");
byte[] fileContent = new byte[(int) file.length()];
try (FileInputStream inputStream = new FileInputStream(file)) {
inputStream.read(fileContent);
} catch (IOException e) {
e.printStackTrace();
}
// Base64编码
String encodedString = Base64.getEncoder().encodeToString(fileContent);
System.out.println("Base64编码后的字符串:" + encodedString);
// Base64解码
byte[] decodedBytes = Base64.getDecoder().decode(encodedString);
String decodedString = new String(decodedBytes);
System.out.println("Base64解码后的字符串:" + decodedString);
// 写入文件
try (FileOutputStream outputStream = new FileOutputStream("test_decoded.txt")) {
outputStream.write(decodedBytes);
} catch (IOException e) {
e.printStackTrace();
}
}
}
```
说明:
1. 首先,读取文件内容,将其存储在一个字节数组中。
2. 使用`Base64.getEncoder()`方法获取Base64编码器,将字节数组进行编码,得到Base64编码后的字符串。
3. 使用`Base64.getDecoder()`方法获取Base64解码器,将Base64编码后的字符串进行解码,得到字节数组。
4. 将字节数组写入文件中,即可得到解码后的文件。
相关推荐
![](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)