PDF 到字节数组,反之亦然
问题描述:
我需要将 pdf 转换为字节数组,反之亦然.
I need to convert pdf to byte array and vice versa.
有人可以帮我吗?
这就是我如何转换为字节数组
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.但它说 '格式错误.不是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);
}
答
Java 7 引入了 Files.readAllBytes()
,可以将 PDF 读入 byte[]
像这样:
Java 7 introduced Files.readAllBytes()
, which can read a PDF into a byte[]
like so:
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.Files;
Path pdfPath = Paths.get("/path/to/file.pdf");
byte[] pdf = Files.readAllBytes(pdfPath);
感谢 Farooque 指出:这适用于阅读任何类型的文件,而不仅仅是 PDF.所有文件最终都只是一堆字节,因此可以读入byte[]
.
Thanks Farooque for pointing out: this will work for reading any kind of file, not just PDFs. All files are ultimately just a bunch of bytes, and as such can be read into a byte[]
.