java 如何用java知道文件是否已损坏(可读)?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10477327/
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 know with java whether file is corrupted (readable) or not?
提问by DHRUV BANSAL
I have web application where person can upload any pdf via FTP. After pdf file get uploaded I perform certain operations over that pdf.
我有网络应用程序,人们可以通过 FTP 上传任何 pdf。pdf 文件上传后,我对该 pdf 执行某些操作。
But the problem here is, while uploading the PDF via FTP sometimes connection breaks up in between and the pdf uploaded is not complete (act like corrupted one). When I try to open that document in arobat reader it gives message 'There was an error opening the document. The file is damaged and could not be repaired'.
但这里的问题是,当通过 FTP 上传 PDF 时,有时连接中断,上传的 pdf 不完整(就像损坏的一样)。当我尝试在 robat 阅读器中打开该文档时,它给出消息“打开文档时出错。文件已损坏,无法修复'。
Now before starting processing over PDF, I want to check whether pdf uploaded is readable means no corrupted.
现在在开始处理 PDF 之前,我想检查上传的 pdf 是否可读意味着没有损坏。
Do java provide any API for that, or there is any method to check whether file is corrupted or not.
java是否为此提供了任何API,或者有任何方法可以检查文件是否已损坏。
回答by Ravinder Reddy
We have iText APIin Java to work on PDF files.
我们有Java 中的iText API来处理 PDF 文件。
To check if a PDF file is valid to load and read, use com.itextpdf.text.pdf.PdfReader
.
If the file is corrupted, an exception like com.itextpdf.text.exceptions.InvalidPdfException
, is thrown.
要检查 PDF 文件是否可有效加载和阅读,请使用com.itextpdf.text.pdf.PdfReader
.
如果文件已损坏com.itextpdf.text.exceptions.InvalidPdfException
,则会引发 , 之类的异常。
Sample code snippet:
示例代码片段:
...
import com.itextpdf.text.pdf.PdfReader;
...
try {
PdfReader pdfReader = new PdfReader( pathToUploadedPdfFile );
String textFromPdfFilePageOne = PdfTextExtractor.getTextFromPage( pdfReader, 1 );
System.out.println( textFromPdfFilePageOne );
}
catch ( Exception e ) {
// handle exception
}
In case of uploaded but corrupted files, you may face the following error:
如果上传但损坏的文件,您可能会遇到以下错误:
com.itextpdf.text.exceptions.InvalidPdfException: Rebuild failed:
trailer not found.; Original message: PDF startxref not found.
Note: To produce such an exception, try saving a pdf file from net, but abort it in the middle.
Use it to load through above code snippetand check if it is loaded safe.
注意:要产生这样的异常,请尝试从网络保存一个 pdf 文件,但在中间中止它。
使用它来加载上面的代码片段并检查它是否安全加载。
You can find detailed examples on iText API at
您可以在以下位置找到有关 iText API 的详细示例