基于springboot实现查询zip压缩包中word文件的页数
时间: 2023-12-24 15:02:01 浏览: 76
实现思路:
1. 使用java.util.zip包中的ZipFile类读取zip压缩包;
2. 遍历zip压缩包中的所有文件,使用Apache POI库读取word文件的页数;
3. 将每个word文件的页数累加,得到zip压缩包中所有word文件的总页数。
代码实现:
1. 添加依赖
在pom.xml文件中添加以下依赖:
```
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>4.1.2</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>4.1.2</version>
</dependency>
```
2. 编写代码
ZipUtil.java
```
import java.io.File;
import java.io.IOException;
import java.util.Enumeration;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.apache.poi.xwpf.usermodel.XWPFParagraph;
public class ZipUtil {
public static int getTotalPageNum(String zipFilePath) throws IOException {
int totalPageNum = 0;
ZipFile zipFile = new ZipFile(new File(zipFilePath));
Enumeration<? extends ZipEntry> entries = zipFile.entries();
while (entries.hasMoreElements()) {
ZipEntry entry = entries.nextElement();
if (!entry.isDirectory() && entry.getName().endsWith(".docx")) {
XWPFDocument doc = new XWPFDocument(zipFile.getInputStream(entry));
int pageNum = doc.getProperties().getExtendedProperties().getPages();
totalPageNum += pageNum;
doc.close();
}
}
zipFile.close();
return totalPageNum;
}
}
```
ZipController.java
```
import java.io.IOException;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class ZipController {
@GetMapping("/totalPageNum")
public int getTotalPageNum(@RequestParam String zipFilePath) throws IOException {
return ZipUtil.getTotalPageNum(zipFilePath);
}
}
```
3. 测试
启动springboot应用,访问http://localhost:8080/totalPageNum?zipFilePath=xxx.zip,其中xxx.zip为要查询的zip压缩包的路径。如:
http://localhost:8080/totalPageNum?zipFilePath=D:/test.zip
返回结果为zip压缩包中所有word文件的总页数。
阅读全文