最近利用爬虫上网下了很多pdf文档,但有一小部分由于网络不稳定等原因,在下载过程中出现了错误,而网上又缺少批量判断的工具,因此调研了一些开源工具,写了一个小程序!
需要的jar包:
1、bouncycastle.jar http://d.download.csdn.net/down/474865/dog3752
2、iText 5.0.2.jar http://download.csdn.net/source/2262675
思路:
首先得到给定目录下的所有pdf文件,然后利用itext包来读取pdf,如果读取成功,则无错!否则出错!
import java.io.File;
import java.io.FileFilter;
/*pdf文件过滤器
*/
public class PdfFileFilter implements FileFilter {
public boolean accept(File file) {
if (file.isFile()) {
String filename = file.getName().toLowerCase();
if (filename.endsWith(".pdf") == true) {
return true;
} else {
return false;
}
} else {
return true;
}
}
}
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import com.lowagie.text.Document;
import com.lowagie.text.pdf.PdfReader;
public class PDFCheck {
private static ArrayList<String> pdffiles = new ArrayList<String>();
/**
* 递归得到特定目录下的所有文件
*/
public static void getAllPdfFile(String basedir) {
File dir = new File(basedir);
File[] files = dir.listFiles(new PdfFileFilter());
if (files == null)
return;
for (int i = 0; i < files.length; i++) {
if (files[i].isDirectory()) {
getAllPdfFile(files[i].getAbsolutePath());
} else {
pdffiles.add(files[i].getAbsolutePath());
}
}
}
/**
* 循环检测
*/
private static void CheckPdfFiles(ArrayList<String> files) {
for (String file : files) {
boolean flag = false;
flag = check(file);
if(!flag){
System.out.println(file+"文件损坏");
}
}
}
/**
* 利用itext打开pdf文档
*/
private static boolean check(String file) {
boolean flag1 = false;
int n = 0;
try {
Document document = new Document(new PdfReader(file).getPageSize(1));
document.open();
PdfReader reader = new PdfReader(file);
n = reader.getNumberOfPages();
if (n != 0)
flag1 = true;
document.close();
} catch (IOException e) {
e.printStackTrace();
}
return flag1;
}
public static void main(String[] args) {
getAllPdfFile("D:\\WO\\");
if(pdffiles.size()>0)CheckPdfFiles(pdffiles);
}
}