如何用java知道文件是否已损坏(可读)? [英] How to know with java whether file is corrupted (readable) or not?

查看:1746
本文介绍了如何用java知道文件是否已损坏(可读)?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有网络应用程序,人们可以通过FTP上传任何pdf。 pdf文件上传后,我对该pdf执行某些操作。

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已上传是不完整的(行为像腐败的一样)。当我尝试在arobat阅读器中打开该文档时,它会显示消息'打开文档时出错。该文件已损坏且无法修复'。

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'.

现在,在开始处理PDF之前,我想检查上传的pdf是否可读意味着没有损坏。

Now before starting processing over PDF, I want to check whether pdf uploaded is readable means no corrupted.

java是否为此提供任何API,或者有任何方法来检查文件是否已损坏。

Do java provide any API for that, or there is any method to check whether file is corrupted or not.

推荐答案

我们有 iText API 用Java来处理PDF文件。

We have iText API in Java to work on PDF files.

要检查PDF文件是否有效加载和读取,请使用 com.itextpdf.text.pdf.PdfReader 。$
如果文件已损坏,则抛出类似 com.itextpdf.text.exceptions.InvalidPdfException 的异常。

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.

示例代码段

...  
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.  

注意:要产生此类异常,请尝试保存pdf文件net,但在中间中止。

用它来加载上面的代码片段并检查它是否安全加载。

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 snippet and check if it is loaded safe.

您可以在iText API上找到详细的示例, 此处

You can find detailed examples on iText API, here.

这篇关于如何用java知道文件是否已损坏(可读)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆