java 压缩.gz

public class GzipPcompress {

public static void main(String args[]) {
GzipPcompress gzip = new GzipPcompress() ;
String sourcePathAndName = "F:/download/20150819.txt" ;
String pressPathAndName = "F:/download/a.gz" ;
gzip.gzPressFile(sourcePathAndName, pressPathAndName);

}

public void gzPressFile(String sourcePathAndName ,String pressPathAndName ){
try {
BufferedReader in = new BufferedReader(new FileReader(sourcePathAndName));

BufferedOutputStream out = new BufferedOutputStream(
new GZIPOutputStream(new FileOutputStream(pressPathAndName)));
int c;
while ((c = in.read()) != -1) {
out.write(c);
}
in.close();
out.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
要在 Java 中进行 tar.gz 压缩,可以使用 Java 中的 GZIPOutputStream 和 TarArchiveOutputStream 类。下面是一个简单的示例代码: ```java import org.apache.commons.compress.archivers.tar.TarArchiveEntry; import org.apache.commons.compress.archivers.tar.TarArchiveOutputStream; import org.apache.commons.compress.compressors.gzip.GzipCompressorOutputStream; import java.io.*; public class TarGzExample { public static void main(String[] args) throws Exception { // 源文件或目录 File source = new File("path/to/source"); // 目标文件 File target = new File("path/to/target.tar.gz"); // 创建 GzipCompressorOutputStream FileOutputStream fos = new FileOutputStream(target); GzipCompressorOutputStream gos = new GzipCompressorOutputStream(fos); // 创建 TarArchiveOutputStream TarArchiveOutputStream tos = new TarArchiveOutputStream(gos); // 添加文件或目录 addFileToTarGz(tos, source, ""); // 关闭流 tos.close(); gos.close(); fos.close(); } private static void addFileToTarGz(TarArchiveOutputStream tos, File file, String parent) throws Exception { // 创建 TarArchiveEntry TarArchiveEntry entry = new TarArchiveEntry(file, parent + file.getName()); // 如果是目录,递归添加子文件或子目录 if (file.isDirectory()) { for (File child : file.listFiles()) { addFileToTarGz(tos, child, entry.getName() + "/"); } return; } // 添加 TarArchiveEntry tos.putArchiveEntry(entry); // 入文件内容 FileInputStream fis = new FileInputStream(file); byte[] buffer = new byte[1024]; int len; while ((len = fis.read(buffer)) != -1) { tos.write(buffer, 0, len); } fis.close(); // 关闭 TarArchiveEntry tos.closeArchiveEntry(); } } ``` 这里使用了第三方库 Apache Commons Compress 来简化操作,可以通过 Maven 导入: ```xml <dependency> <groupId>org.apache.commons</groupId> <artifactId>commons-compress</artifactId> <version>1.20</version> </dependency> ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值