我试图从通过网络服务返回的字节数组中生成PDF,但是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();
以下是来自我们的 Web 服务的 JSON:
{"PDF details": {
"id":"121",
"pdf bytearray":"[B@62a58cd"
}
}
以下是我的webservice代码,它会在json中输出bytearray:
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();
}
pdf bytearray
不合法,你需要修复该网络服务。 - 1615903[B
)后跟@
再跟上哈希码(62a58cd
)的字符串。你应该能够自己意识到整个 PDF 文档不可能适合 10 个字符。使用 base-64 将 pdf 字节转换为可打印字符串,反之亦然。 - JB Nizet