如何在 Java 中将 Blob 对象转换为 PDF 文件?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/28220352/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to convert a Blob object into a PDF file in Java?
提问by AndreaNobili
I have the following situation into a Java application.
我在 Java 应用程序中遇到了以下情况。
From the database a retrieve this Blobobject that is the representation of a PDF file on the DB:
从数据库中检索此Blob对象,该对象是 DB 上 PDF 文件的表示形式:
Blob blobPdf = cedolinoPdf.getAllegatoBlob();
Now I have to convert it into a PDF file. How can I do this task?
现在我必须将其转换为 PDF 文件。我怎样才能完成这个任务?
Tnx
Tnx
采纳答案by Tanmoy Bhattacharjee
You can use the getBinaryStream() from the ResultSet, then you can create a file from InputStream returned by the getBinaryStream().
您可以使用 ResultSet 中的 getBinaryStream(),然后您可以从 getBinaryStream() 返回的 InputStream 创建一个文件。
Your code may look something like this
您的代码可能如下所示
Connection connection = null;
Statement statement = null;
ResultSet rs = null;
try {
Class.forName("net.sourceforge.jtds.jdbc.Driver").newInstance();
connection = DriverManager.getConnection(connectionURL, "sa", "sa");
statement = connection.createStatement();
rs = statement.executeQuery("SELECT fileName,blobFile FROM tblBlobFiles");
if (rs.next()) {
String filename = rs.getString(1);
Blob blob = rs.getBlob(2);
InputStream is = blob.getBinaryStream();
FileOutputStream fos = new FileOutputStream("C:\DownloadedFiles"+ "\" + filename);
int b = 0;
while ((b = is.read()) != -1)
{
fos.write(b);
}
}
} catch (IOException e)
{
e.getMessage (); e.printStackTrace();
System.out.println(e);
}
catch (SQLException e)
{
e.getMessage (); e.printStackTrace();
System.out.println(e);
}
If you need all the blobs, do a iteration on the resultset
如果需要所有 blob,请对结果集进行迭代
回答by BretC
If the Blob is the binary representation of a PDF, all you need to do is get the bytes. If you wanted to write the PDF to a file, you could do...
如果 Blob 是 PDF 的二进制表示,您需要做的就是获取字节。如果您想将 PDF 写入文件,您可以这样做...
Blob blobPdf = ...;
File outputFile = new File("/tmp/blah/whatever.pdf");
FileOutputStream fout = new FileOutputStream(outputFile);
IOUtils.copy(blobPdf.getBinaryStream(), fout);
This should write your PDF to a file called "/tmp/blah/whatever.pdf"
这应该将您的 PDF 写入一个名为“/tmp/blah/whatever.pdf”的文件
回答by Gaurab Pradhan
you can use Java NIO
你可以使用 Java NIO
InputStream fileBolb = rs.getBinaryStream("columnName");
ReadableByteChannel rbc = Channels.newChannel(fileBolb );
FileOutputStream fos = new FileOutputStream(filePath + fname);
fos.getChannel().transferFrom(rbc, 0, Long.MAX_VALUE);
fos.close();
rbc.close();