Java将多个.docx文件全部打包为.zip压缩包
时间: 2023-12-15 19:06:56 浏览: 234
要将多个.docx文件打包为一个.zip压缩包,你可以使用Java的java.util.zip包和java.io包。以下是一个示例代码:
```java
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
public class ZipMultipleDocxFiles {
public static void main(String[] args) {
List<String> docxFiles = new ArrayList<>();
docxFiles.add("path/to/docx/file1.docx");
docxFiles.add("path/to/docx/file2.docx");
docxFiles.add("path/to/docx/file3.docx");
String zipFilePath = "path/to/zip/file.zip";
try {
// 创建输出流
FileOutputStream fos = new FileOutputStream(zipFilePath);
ZipOutputStream zos = new ZipOutputStream(fos);
// 逐个文件将docx文件添加到ZipOutputStream中
for (String docxFilePath : docxFiles) {
File docxFile = new File(docxFilePath);
FileInputStream fis = new FileInputStream(docxFile);
// 创建ZipEntry并添加到ZipOutputStream中
ZipEntry zipEntry = new ZipEntry(docxFile.getName());
zos.putNextEntry(zipEntry);
// 将docx文件内容写入ZipOutputStream
byte[] buffer = new byte[1024];
int bytesRead;
while ((bytesRead = fis.read(buffer)) != -1) {
zos.write(buffer, 0, bytesRead);
}
// 关闭当前ZipEntry的输入流
fis.close();
zos.closeEntry();
}
// 关闭ZipOutputStream
zos.close();
System.out.println("打包成功!");
} catch (IOException e) {
System.out.println("打包失败:" + e.getMessage());
}
}
}
```
请将`docxFiles`列表中的文件路径替换为你实际的.docx文件路径。运行以上代码后,将会在指定的路径生成一个名为"file.zip"的压缩文件,其中包含了你指定的多个.docx文件。
此代码示例会逐个将.docx文件添加到压缩文件中,并在压缩文件中创建与每个.docx文件名称相对应的ZipEntry。请确保文件路径正确,并注意文件名在压缩文件中的唯一性。
阅读全文
相关推荐
![docx](https://img-home.csdnimg.cn/images/20241231044901.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![docx](https://img-home.csdnimg.cn/images/20241231044901.png)
![docx](https://img-home.csdnimg.cn/images/20241231044901.png)
![docx](https://img-home.csdnimg.cn/images/20241231044901.png)
![docx](https://img-home.csdnimg.cn/images/20241231044901.png)
![docx](https://img-home.csdnimg.cn/images/20241231044901.png)
![docx](https://img-home.csdnimg.cn/images/20241231044901.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![](https://img-home.csdnimg.cn/images/20250102104920.png)
![](https://img-home.csdnimg.cn/images/20250102104920.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)