【问题标题】:Decoding base64 data and not able to download as a file解码 base64 数据,无法下载为文件
【发布时间】:2018-07-22 21:13:26
【问题描述】:

我正在以 String 格式获取 base64 编码数据。我正在尝试解码 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 版本

【问题讨论】:

  • 什么错误?请发布您在问题中遇到的错误

标签: java java-8 base64


【解决方案1】:

Writers 用于写入字符,而不是字节。要写入字节,您应该使用OutputStream 的一些风格。见Writer or OutputStream?

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

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

【讨论】:

    【解决方案2】:
    import java.io.BufferedWriter;
    import java.io.File;
    import java.io.FileWriter;
    import java.io.IOException;
    import java.nio.charset.StandardCharsets;
    import java.util.Base64;
    
    public class Example {
    
    public static void main(String[] args) {
    
        String contentByte="Simple text send from server";
        byte[] bytes = 
        Base64.getEncoder().encode(contentByte.getBytes(StandardCharsets.UTF_8));
        //Data received by you at server end(base64 encoded data as string)
        contentByte = new String(bytes);
    
        System.out.println(new String(bytes));
    
        BufferedWriter out = null;
        System.out.println("Bytes --->"+contentByte);
        try {
            File file = File.createTempFile("Testing",".pdf", new File("/tmp/") );
           // file.deleteOnExit(); // this line will remove file and your data will not going to save to file. So remove this line.
            out = new BufferedWriter(new FileWriter(file));
            byte[] decodedImg = 
          Base64.getDecoder().decode(contentByte.getBytes(StandardCharsets.UTF_8));
            out.write(new String(decodedImg)); //getting error on this line
    
        }catch (Exception e)
        {
            e.printStackTrace();
        }finally {
            if(out!=null)
            {
                try {
                    out.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
       }
     }
    

    以上解决方案可能对您有所帮助。

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-09-16
    • 2021-04-24
    • 2014-03-29
    • 2017-04-07
    • 1970-01-01
    • 2012-05-19
    相关资源
    最近更新 更多