以下是一个使用Java遍历文件夹并将文件压缩成tar.gz格式的示例代码。如果压缩过程中出现异常,会捕获并报告错误:
java
Copy code
import java.io.*;
import java.util.zip.*;
import org.apache.commons.compress.archivers.tar.*;
public class FileCompression {
public static void main(String[] args) {
String folderPath = "/path/to/folder"; // 文件夹路径
String outputFilePath = "/path/to/output.tar.gz"; // 输出文件路径
try {
File folder = new File(folderPath);
FileOutputStream fos = new FileOutputStream(outputFilePath);
BufferedOutputStream bos = new BufferedOutputStream(fos);
GZIPOutputStream gzos = new GZIPOutputStream(bos);
TarArchiveOutputStream tos = new TarArchiveOutputStream(gzos);
compressFolder(folder, tos, "");
tos.finish();
tos.close();
System.out.println("文件压缩完成。");
} catch (IOException e) {
e.printStackTrace();
System.err.println("文件压缩失败:" + e.getMessage());
}
}
private static void compressFolder(File folder, TarArchiveOutputStream tos, String parentDir) throws IOException {
File[] files = folder.listFiles();
byte[] buffer = new byte[1024];
for (File file : files) {
if (file.isDirectory()) {
continue; // 跳过自身的文件夹
}
FileInputStream fis = new FileInputStream(file);
BufferedInputStream bis = new BufferedInputStream(fis);
String entryName = parentDir + file.getName();
TarArchiveEntry entry = new TarArchiveEntry(file, entryName);
tos.putArchiveEntry(entry);
int bytesRead;
while ((bytesRead = bis.read(buffer)) != -1) {
tos.write(buffer, 0, bytesRead);
}
bis.close();
tos.closeArchiveEntry();
}
}
}
请确保将/path/to/folder替换为你想要遍历的文件夹路径,将/path/to/output.tar.gz替换为输出tar.gz文件的路径。此代码使用java.util.zip和org.apache.commons.compress.archivers.tar库来实现文件的压缩。如果发生异常,将打印堆栈跟踪并报告错误消息。在compressFolder方法中,我们添加了一个条件来跳过自身的文件夹,只处理文件。