我试图从Java中的字节数组生成PDf,该数组是通过Web服务返回的,但PDF无法打开。它显示它已损坏,我已附上我的代码。有人请帮助我解决哪里错了吗?
JSONObject o = new JSONObject(outjson);
JSONObject jsonob = o.optJSONObject("PDF details");
byte[] pdfbyte=jsonob.optString("pdf bytearray").toString().getBytes();
String str1 = new String(pdfbyte);
File someFile = new File("C:/Users/acer/Desktop/test1.pdf");
FileOutputStream fos = new FileOutputStream(someFile);
byte[] byteData = str1.getBytes();
byte[] byteData1 = test.getBytes();
fos.write(pdfbyte);
fos.flush();
fos.close();
以下是我来自网络服务的 JSON:
{"PDF details": {
"id":"121",
"pdf bytearray":"[B@62a58cd"
}
}
以下是我的 Web 服务代码,它以 json 形式输出字节数组:
public Response getPdf( )
{
String flag=null;
File file = new File("C:/Users/acer/Desktop/Report.pdf");
FileInputStream fileInputStream;
byte[] data = null;
byte[] finalData = null;
ByteArrayOutputStream byteArrayOutputStream = null;
fileInputStream = new FileInputStream(file);
data = new byte[(int)file.length()];
finalData = new byte[(int)file.length()];
byteArrayOutputStream = new ByteArrayOutputStream();
fileInputStream.read(data);
byteArrayOutputStream.write(data);
finalData = byteArrayOutputStream.toByteArray();
fileInputStream.close();
System.out.println(finalData);
JSONObject jsonObject = new JSONObject();
JSONObject mainjsonObject = new JSONObject();
jsonObject.put("id","121");
jsonObject.put("pdf bytearray",finalData);
mainjsonObject.put("PDF details",jsonObject);
flag = "" + mainjsonObject;
return Response.status(200).entity(flag).build();
}
最佳答案
我在我的网络服务中进行了以下更改:
public Response getPdf( )
{
String flag=null;
File file = new File("C:/Users/acer/Desktop/Report.pdf");
FileInputStream fileInputStreamReader = new FileInputStream(file);
byte[] bytes = new byte[(int)file.length()];
fileInputStreamReader.read(bytes);
String encodedBase64 = new String(Base64.encodeBase64(bytes));
JSONObject jsonObject = new JSONObject();
JSONObject mainjsonObject = new JSONObject();
jsonObject.put("id","121");
jsonObject.put("pdf bytearray",encodedBase64);
mainjsonObject.put("PDF details",jsonObject);
flag = "" + mainjsonObject;
return Response.status(200).entity(flag).build();
}
我的客户:
String encodedBase64=jsonob.optString("pdf bytearray");
byte[] decodedBytes = Base64.decodeBase64(encodedBase64);
System.out.println("decbyte "+decodedBytes);
File someFile = new File("C:/Users/acer/Desktop/test.pdf");
OutputStream fos = new FileOutputStream(someFile);
fos.write(decodedBytes);
fos.flush();
fos.close();
关于java - 从字节数组创建损坏的 PDF,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45318662/