Java 正在解码base64数据,无法作为文件下载
Am获取base64编码数据,格式为Java 正在解码base64数据,无法作为文件下载,java,java-8,base64,Java,Java 8,Base64,Am获取base64编码数据,格式为Stringformat。我正在尝试解码base64并希望作为文件下载。我已经对下面几行代码进行了注释,我从这些代码中发现了错误 我不知道如何解码数据 String contentByte=null; for (SearchHit contenthit : contentSearchHits) { Map<String, Object> sourceAsMap = contenthit.getSourceAsMap(); file
String
format。我正在尝试解码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
String contentByte=null;
for(SearchHit contenthit:contentSearchHits){
Map sourceAsMap=contenthit.getSourceAsMap();
fileName=sourceAsMap.get(“Name”).toString();
System.out.println(“文件名::”+文件名);
contentByte=sourceAsMap.get(“resume”).toString();
}
System.out.println(“字节-->”+contentByte);
File File=File.createTempFile(“Testing”、“.pdf”、新文件(“D:/”);
deleteOnExit()文件;
BufferedWriter out=新的BufferedWriter(新的文件写入程序(文件));
out.write(Base64.getDecoder().decode(contentByte))//获取此行上的错误
请查找我得到的以下编译错误
类型BufferedWriter中的方法write(int)不适用于参数(字节[])
我使用的是Java8版本
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();
}
}
}
}
}
您可能会得到上述解决方案的帮助。s用于写入字符,而不是字节。要写入字节,您应该使用某种风格的。看
但是,如果您只想将字节数组写入文件,Files
类提供了一种方法,可以执行以下操作:
byte[] bytes = Base64.getDecoder().decode(contentByte);
Files.write(file.toPath(), bytes);
什么错误?请在你的问题中贴出你的错误。你应该了解…