java - 解码 base64 数据,无法下载为文件
问题描述
我正在获取 base64 编码数据作为String
格式。我正在尝试解码 base64 并希望作为文件下载。我已经评论了以下几行代码,这些代码行中出现了错误。
我不确定如何解码数据。
String contentByte=null;
for (SearchHit contenthit : contentSearchHits) {
Map<String, Object> sourceAsMap = contenthit.getSourceAsMap();
fileName=sourceAsMap.get("Name").toString();
System.out.println("FileName ::::"+fileName);
contentByte = sourceAsMap.get("resume").toString();
}
System.out.println("Bytes --->"+contentByte);
File file = File.createTempFile("Testing",".pdf", new File("D:/") );
file.deleteOnExit();
BufferedWriter out = new BufferedWriter(new FileWriter(file));
out.write(Base64.getDecoder().decode(contentByte)); //getting error on this line
请找到以下编译错误。
The method write(int) in the type BufferedWriter is not applicable for the arguments (byte[])
我正在使用 Java 8 版本
解决方案
Writer
s 用于写入字符,而不是字节。要写入字节,您应该使用一些OutputStream
. 请参阅Writer 或 OutputStream?
但是,如果您只想将字节数组写入文件,则Files
类提供了一个 Files.write方法来执行此操作:
byte[] bytes = Base64.getDecoder().decode(contentByte);
Files.write(file.toPath(), bytes);
推荐阅读
- javascript - 我怎样才能得到这个渲染的画布?
- python - 在Python中将二叉树插入矩阵
- c# - 序列化另一个 json 中的 Json 字符串中的问题
- c# - 使用 C# 和 cosmos 客户端从 cosmos db 中删除文档
- java - 创建服务时出现 android.view.WindowManager$BadTokenException 错误
- android - 有没有办法恢复具有密钥库文件、密钥库密码和以前签名的 apk 的别名密钥密码?
- c# - Web应用程序项目之间共享Sqlite
- python - 无法创建菜单 AttributeError:“框架”对象没有属性“tk_menuBar”
- python-3.x - TF 2.0 错误:使用梯度带训练期间变量不存在梯度
- kotlin - kotlin 继承转换导致未使用的属性