相关jar包:
cn.hutool
hutool-core
5.0.4
org.apache.poi
poi-ooxml
4.0.1
org.apache.poi
poi-scratchpad
4.0.1
poi
org.apache.poi
fr.opensagres.xdocreport
fr.opensagres.poi.xwpf.converter.xhtml
2.0.2
package com.xxx;
import cn.hutool.core.io.FileUtil;
import com.itextpdf.text.pdf.PdfReader;
import org.apache.poi.hwpf.extractor.WordExtractor;
import org.apache.poi.ooxml.POIXMLdocument;
import org.apache.poi.openxml4j.util.ZipSecureFile;
import org.apache.poi.xslf.usermodel.XMLSlideShow;
import org.apache.poi.xwpf.usermodel.XWPFdocument;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.List;
public class MainTest {
public static void main(String[] args) throws IOException {
run();
}
public static void run() throws IOException {
List files = FileUtil.loopFiles("D:\题库");
System.out.println("文件总数:" + files.size());
int num = 1;
for (File file : files) {
int count = 0;
//System.out.println(file);
String[] fileTypeArray = file.getName().split("\.");
String fileType = fileTypeArray[fileTypeArray.length - 1];
if ("doc".equals(fileType)) {
count = countWord2003Page(file.getPath());
}
if ("docx".equals(fileType)) {
count = countWord2007Page(file.getPath());
}
if ("pdf".equals(fileType)) {
count = countPdfPage(file.getPath());
}
System.out.println(file + "@" + fileType + "@" + count);
num++;
}
}
public static int countPdfPage(String filepath) {
int pageCount = 0;
PdfReader reader = null;
try {
reader = new PdfReader(filepath);
pageCount = reader.getNumberOfPages();
} catch (IOException e) {
e.printStackTrace();
} finally {
reader.close();
}
return pageCount;
}
public static int countPPTPage(String filePath) throws IOException {
int pageCount = 0;
ZipSecureFile.setMinInflateRatio(-1.0d);
FileInputStream fis = null;
try {
fis = new FileInputStream(filePath);
XMLSlideShow pptxFile = new XMLSlideShow(fis);
pageCount = pptxFile.getSlides().size();
} catch (IOException e) {
e.printStackTrace();
} finally {
fis.close();
}
return pageCount;
}
public static int countWord2007Page(String filePath) {
int pageCount = 0;
ZipSecureFile.setMinInflateRatio(-1.0d);
XWPFdocument docx = null;
try {
docx = new XWPFdocument(POIXMLdocument.openPackage(filePath));
pageCount = docx.getProperties().getExtendedProperties().getUnderlyingProperties().getPages();//总页数
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
docx.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return pageCount;
}
public static int countWord2003Page(String filePath) {
int pageCount = 0;
WordExtractor doc = null;
ZipSecureFile.setMinInflateRatio(-1.0d);
try {
doc = new WordExtractor(new FileInputStream(filePath));//.doc格式Word文件提取器
pageCount = doc.getSummaryInformation().getPageCount();//总页数
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
doc.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return pageCount;
}
}