Java对文件夹内多个CSV文件压缩
在Java中,有时我们需要将一个文件夹内的多个CSV文件压缩成一个ZIP文件,以方便传输或存储。本文将介绍如何使用Java实现这一功能,并提供相应的代码示例。
1. 压缩文件
首先,我们需要用到Java的压缩库,即java.util.zip
包。该包提供了压缩和解压缩文件的功能。
我们可以通过以下步骤来实现文件的压缩:
- 创建一个用于输出压缩文件的
ZipOutputStream
对象。 - 遍历文件夹内的所有CSV文件。
- 对于每个CSV文件,创建一个
FileInputStream
对象用于读取文件内容。 - 创建一个
ZipEntry
对象,设置其名称为CSV文件的名称。 - 将
ZipEntry
对象添加到ZipOutputStream
中。 - 使用缓冲区将CSV文件的内容写入到
ZipOutputStream
中。 - 关闭
ZipOutputStream
和FileInputStream
对象。
以下是代码示例:
import java.io.*;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
public class CSVFileCompressor {
public static void compressFiles(String folderPath, String zipFilePath) {
try {
File folder = new File(folderPath);
File[] files = folder.listFiles();
FileOutputStream fos = new FileOutputStream(zipFilePath);
ZipOutputStream zos = new ZipOutputStream(fos);
for (File file : files) {
if (file.getName().endsWith(".csv")) {
FileInputStream fis = new FileInputStream(file);
ZipEntry zipEntry = new ZipEntry(file.getName());
zos.putNextEntry(zipEntry);
byte[] buffer = new byte[1024];
int length;
while ((length = fis.read(buffer)) > 0) {
zos.write(buffer, 0, length);
}
fis.close();
}
}
zos.close();
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
String folderPath = "/path/to/csv/folder";
String zipFilePath = "/path/to/zip/file.zip";
compressFiles(folderPath, zipFilePath);
}
}
在上述代码中,compressFiles()
方法接受两个参数,分别为文件夹的路径和要输出的ZIP文件的路径。该方法首先获取文件夹内的所有文件,然后遍历每个文件。对于每个CSV文件,它将创建一个FileInputStream
对象读取文件内容,并创建一个ZipEntry
对象设置其名称为文件的名称。然后,它使用ZipOutputStream
将ZipEntry
对象添加到ZIP文件中,并使用缓冲区将文件内容写入ZIP文件。最后,它关闭了所有的流。
在main()
方法中,我们提供了文件夹的路径和ZIP文件的路径作为示例。您可以根据实际情况进行修改。
2. 解压缩文件
如果您需要将压缩文件解压缩成原始的CSV文件,可以使用以下代码示例:
import java.io.*;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;
public class CSVFileExtractor {
public static void extractFiles(String zipFilePath, String outputFolderPath) {
try {
File folder = new File(outputFolderPath);
if (!folder.exists()) {
folder.mkdirs();
}
FileInputStream fis = new FileInputStream(zipFilePath);
ZipInputStream zis = new ZipInputStream(fis);
ZipEntry zipEntry;
while ((zipEntry = zis.getNextEntry()) != null) {
if (!zipEntry.isDirectory()) {
String filePath = outputFolderPath + File.separator + zipEntry.getName();
FileOutputStream fos = new FileOutputStream(filePath);
byte[] buffer = new byte[1024];
int length;
while ((length = zis.read(buffer)) > 0) {
fos.write(buffer, 0, length);
}
fos.close();
}
zis.closeEntry();
}
zis.close();
fis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
String zipFilePath = "/path/to/zip/file.zip";
String outputFolderPath = "/path/to/output/folder";
extractFiles(zipFilePath, outputFolderPath);
}
}
在上述代码中,extractFiles()
方法接受两个参数,分别为ZIP文件的路径和解压缩后输出的文件夹的路径。该方法首先创建输出文件夹(如果不存在),然后创建一个FileInputStream
对象读取ZIP文件内容