PDF到字节数组,反之亦然
问题描述:
我需要将pdf转换为字节数组,反之亦然。
I need to convert pdf to byte array and vice versa.
任何人都可以帮助我吗?
Can any one help me?
这就是我转换为字节数组的方式
This is how I am converting to byte array
public static byte[] convertDocToByteArray(String sourcePath) {
byte[] byteArray=null;
try {
InputStream inputStream = new FileInputStream(sourcePath);
String inputStreamToString = inputStream.toString();
byteArray = inputStreamToString.getBytes();
inputStream.close();
} catch (FileNotFoundException e) {
System.out.println("File Not found"+e);
} catch (IOException e) {
System.out.println("IO Ex"+e);
}
return byteArray;
}
如果我使用以下代码将其转换回文档,则会创建pdf 。但它说的是'Bad Format。不是pdf'
。
If I use following code to convert it back to document, pdf is getting created. But it's saying 'Bad Format. Not a pdf'
.
public static void convertByteArrayToDoc(byte[] b) {
OutputStream out;
try {
out = new FileOutputStream("D:/ABC_XYZ/1.pdf");
out.close();
System.out.println("write success");
}catch (Exception e) {
System.out.println(e);
}
答
你基本上需要一个辅助方法将流读入内存。这很好用:
You basically need a helper method to read a stream into memory. This works pretty well:
public static byte[] readFully(InputStream stream) throws IOException
{
byte[] buffer = new byte[8192];
ByteArrayOutputStream baos = new ByteArrayOutputStream();
int bytesRead;
while ((bytesRead = stream.read(buffer)) != -1)
{
baos.write(buffer, 0, bytesRead);
}
return baos.toByteArray();
}
然后你打电话给:
public static byte[] loadFile(String sourcePath) throws IOException
{
InputStream inputStream = null;
try
{
inputStream = new FileInputStream(sourcePath);
return readFully(inputStream);
}
finally
{
if (inputStream != null)
{
inputStream.close();
}
}
}
不要混合文本和二进制数据 - 它只会导致眼泪。
Don't mix up text and binary data - it only leads to tears.