首页 > 解决方案 > 解码 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 版本

标签: javajava-8base64

解决方案


Writers 用于写入字符,而不是字节。要写入字节,您应该使用一些OutputStream. 请参阅Writer 或 OutputStream?

但是,如果您只想将字节数组写入文件,则Files类提供了一个 Files.write方法来执行此操作:

byte[] bytes = Base64.getDecoder().decode(contentByte);
Files.write(file.toPath(), bytes);

推荐阅读