我需要将pdf转换为字节数组,反之亦然.
谁能帮我?
这就是我转换为字节数组的方式
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;
}
Run Code Online (Sandbox Code Playgroud)
如果我使用以下代码将其转换回文档,则会创建pdf.但是它说'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);
}
Run Code Online (Sandbox Code Playgroud)
Jon*_*eet 32
您基本上需要一个帮助方法来将流读入内存.这非常有效:
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();
}
Run Code Online (Sandbox Code Playgroud)
然后你打电话给:
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();
}
}
}
Run Code Online (Sandbox Code Playgroud)
不要混淆文本和二进制数据 - 它只会导致眼泪.
Chr*_*ark 29
引入了Java 7 Files.readAllBytes(),它可以将PDF读入byte[]如下:
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);
Run Code Online (Sandbox Code Playgroud)
编辑:
感谢Farooque指出:这将适用于阅读任何类型的文件,而不仅仅是PDF.所有文件最终只是一堆字节,因此可以读入a byte[].
Mar*_*ark 11
问题是,您呼叫toString()的对InputStream对象本身.这将返回对象的String表示而InputStream不是实际的PDF文档.
您只想将PDF作为字节读取,因为PDF是二进制格式.然后,您将能够写出相同的byte数组,它将是一个有效的PDF,因为它尚未被修改.
例如,将文件作为字节读取
File file = new File(sourcePath);
InputStream inputStream = new FileInputStream(file);
byte[] bytes = new byte[file.length()];
inputStream.read(bytes);
Run Code Online (Sandbox Code Playgroud)
您可以使用它Apache Commons IO而不必担心内部细节.
使用org.apache.commons.io.FileUtils.readFileToByteArray(File file)返回类型的数据byte[].
pli*_*nth -2
PDF 可能包含二进制数据,并且当您执行 ToString 时它很可能会被破坏。在我看来你想要这个:
FileInputStream inputStream = new FileInputStream(sourcePath);
int numberBytes = inputStream .available();
byte bytearray[] = new byte[numberBytes];
inputStream .read(bytearray);
Run Code Online (Sandbox Code Playgroud)