Java打成各種壓縮包的方法詳細(xì)匯總
1.將指定目錄下的文件打包成 .zip
代碼示例:
import java.io.*; import java.util.zip.*; public class ZipFiles { public static void main(String[] args) { // 要壓縮的文件或文件夾 String sourceFile = "path/to/your/source/file_or_folder"; // 壓縮后的ZIP文件名 String zipFileName = "output.zip"; // 創(chuàng)建一個(gè)輸出流將數(shù)據(jù)寫入ZIP文件 try (FileOutputStream fos = new FileOutputStream(zipFileName); ZipOutputStream zos = new ZipOutputStream(fos)) { // 調(diào)用遞歸方法壓縮文件或文件夾 addToZipFile(sourceFile, sourceFile, zos); System.out.println("文件已成功打包成 " + zipFileName); } catch (IOException e) { e.printStackTrace(); } } private static void addToZipFile(String path, String sourceFile, ZipOutputStream zos) throws IOException { File file = new File(sourceFile); // 如果是文件夾,則獲取其內(nèi)容并遞歸調(diào)用此方法 if (file.isDirectory()) { String[] fileList = file.list(); if (fileList != null) { for (String fileName : fileList) { addToZipFile(path, sourceFile + File.separator + fileName, zos); } } return; } // 如果是文件,則將其添加到ZIP文件中 try (FileInputStream fis = new FileInputStream(sourceFile)) { String entryName = sourceFile.substring(path.length() + 1); // 獲取ZIP中的條目名稱 ZipEntry zipEntry = new ZipEntry(entryName); zos.putNextEntry(zipEntry); byte[] bytes = new byte[1024]; int length; while ((length = fis.read(bytes)) >= 0) { zos.write(bytes, 0, length); } } } }
將 path/to/your/source/file_or_folder
替換為要打包的文件或文件夾的路徑,然后運(yùn)行該代碼。它將創(chuàng)建一個(gè)名為 output.zip
的ZIP文件,其中包含指定路徑下的文件或文件夾。
2.將指定目錄下的文件打包成 .tar.gz
可以使用 Java 中的 java.util.zip
包來創(chuàng)建 .tar.gz
文件。盡管 Java 的標(biāo)準(zhǔn)庫(kù)沒有直接提供對(duì) .tar
格式的支持,但你可以使用 TarArchiveOutputStream
以及 GzipCompressorOutputStream
來創(chuàng)建 tar.gz
歸檔文件。以下是一個(gè)示例:
import org.apache.commons.compress.archivers.tar.*; import org.apache.commons.compress.compressors.gzip.GzipCompressorOutputStream; import java.io.*; public class TarGzFiles { public static void main(String[] args) { // 要壓縮的文件或文件夾 String sourceFile = "path/to/your/source/file_or_folder"; // 壓縮后的tar.gz文件名 String tarGzFileName = "output.tar.gz"; try { FileOutputStream fos = new FileOutputStream(tarGzFileName); BufferedOutputStream bos = new BufferedOutputStream(fos); GzipCompressorOutputStream gzos = new GzipCompressorOutputStream(bos); TarArchiveOutputStream tarArchive = new TarArchiveOutputStream(gzos); File file = new File(sourceFile); addToTarArchive(file, tarArchive); tarArchive.finish(); tarArchive.close(); System.out.println("文件已成功打包成 " + tarGzFileName); } catch (IOException e) { e.printStackTrace(); } } private static void addToTarArchive(File file, TarArchiveOutputStream tarArchive) throws IOException { String entryName = file.getName(); TarArchiveEntry tarEntry = new TarArchiveEntry(file, entryName); tarArchive.putArchiveEntry(tarEntry); if (file.isFile()) { try (FileInputStream fis = new FileInputStream(file)) { byte[] buffer = new byte[1024]; int len; while ((len = fis.read(buffer)) != -1) { tarArchive.write(buffer, 0, len); } tarArchive.closeArchiveEntry(); } } else if (file.isDirectory()) { tarArchive.closeArchiveEntry(); File[] children = file.listFiles(); if (children != null) { for (File child : children) { addToTarArchive(child, tarArchive); } } } } }
在此示例中,使用了 Apache Commons Compress 庫(kù),你可以在 Maven =添加以下依賴:
Maven:
<dependency> <groupId>org.apache.commons</groupId> <artifactId>commons-compress</artifactId> <version>1.21</version> <!-- 或者更高的版本 --> </dependency>
確保將 path/to/your/source/file_or_folder
替換為要打包的文件或文件夾的實(shí)際路徑,然后運(yùn)行代碼以創(chuàng)建 output.tar.gz
文件。
3.將指定目錄下的文件打包成 .tar
Java的標(biāo)準(zhǔn)庫(kù)中并沒有直接支持創(chuàng)建.tar
格式文件的類,但你可以使用Apache Commons Compress庫(kù)來完成這個(gè)任務(wù)。下面是一個(gè)示例代碼:
首先,確保你在項(xiàng)目中包含了Apache Commons Compress庫(kù)。如果使用Maven,可以在pom.xml
文件中添加以下依賴項(xiàng):
<dependency> <groupId>org.apache.commons</groupId> <artifactId>commons-compress</artifactId> <version>1.21</version> <!-- 或者更高的版本 --> </dependency>
然后,使用以下代碼將文件打包成.tar
文件:
import org.apache.commons.compress.archivers.tar.*; import org.apache.commons.compress.utils.IOUtils; import java.io.*; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; public class TarFiles { public static void main(String[] args) { // 要打包的文件或文件夾 String sourceFile = "path/to/your/source/file_or_folder"; // 打包后的tar文件名 String tarFileName = "output.tar"; try { FileOutputStream fos = new FileOutputStream(tarFileName); BufferedOutputStream bos = new BufferedOutputStream(fos); TarArchiveOutputStream tarArchive = new TarArchiveOutputStream(bos); addToTarArchive(sourceFile, tarArchive); tarArchive.finish(); tarArchive.close(); System.out.println("文件已成功打包成 " + tarFileName); } catch (IOException e) { e.printStackTrace(); } } private static void addToTarArchive(String filePath, TarArchiveOutputStream tarArchive) throws IOException { Path sourcePath = Paths.get(filePath); String baseDir = sourcePath.getFileName().toString(); Files.walk(sourcePath) .filter(path -> !Files.isDirectory(path)) .forEach(path -> { try { String entryName = baseDir + File.separator + sourcePath.relativize(path).toString(); TarArchiveEntry tarEntry = new TarArchiveEntry(path.toFile(), entryName); tarArchive.putArchiveEntry(tarEntry); FileInputStream fis = new FileInputStream(path.toFile()); IOUtils.copy(fis, tarArchive); fis.close(); tarArchive.closeArchiveEntry(); } catch (IOException e) { e.printStackTrace(); } }); } }
在這個(gè)示例中,我們使用了Apache Commons Compress庫(kù)來創(chuàng)建.tar
文件。確保將path/to/your/source/file_or_folder
替換為你要打包的實(shí)際文件或文件夾的路徑,并運(yùn)行代碼來創(chuàng)建output.tar
文件。
4.將指定目錄下的文件打包成 .rar
在Java中,壓縮成RAR格式的操作稍微有些復(fù)雜,因?yàn)镽AR格式是一種專有格式,并沒有Java標(biāo)準(zhǔn)庫(kù)提供直接支持。為了壓縮文件為RAR格式,你可以使用第三方庫(kù),比如通過調(diào)用WinRAR或其他命令行工具來實(shí)現(xiàn)。
一種方法是使用Java的ProcessBuilder
來運(yùn)行命令行來執(zhí)行WinRAR或其他RAR壓縮工具的命令。以下是一個(gè)簡(jiǎn)單的示例,假設(shè)你已經(jīng)安裝了WinRAR并將其路徑添加到了系統(tǒng)的環(huán)境變量中:
import java.io.*; public class RARFiles { public static void main(String[] args) { // 要壓縮的文件或文件夾 String sourceFile = "path/to/your/source/file_or_folder"; // 壓縮后的RAR文件名 String rarFileName = "output.rar"; try { // 構(gòu)建命令行 String[] command = {"cmd", "/c", "rar", "a", "-r", rarFileName, sourceFile}; // 創(chuàng)建進(jìn)程并執(zhí)行命令 ProcessBuilder processBuilder = new ProcessBuilder(command); Process process = processBuilder.start(); // 讀取進(jìn)程輸出(可選) BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream())); String line; while ((line = reader.readLine()) != null) { System.out.println(line); } // 等待進(jìn)程執(zhí)行結(jié)束 int exitCode = process.waitFor(); if (exitCode == 0) { System.out.println("文件已成功打包成 " + rarFileName); } else { System.out.println("打包過程中出現(xiàn)錯(cuò)誤"); } } catch (IOException | InterruptedException e) { e.printStackTrace(); } } }
請(qǐng)?zhí)鎿Q path/to/your/source/file_or_folder
為你要壓縮的文件或文件夾的路徑,并確保系統(tǒng)中已經(jīng)正確安裝和配置了WinRAR。
記住,這種方法需要系統(tǒng)中安裝有WinRAR并且路徑被正確添加到系統(tǒng)的環(huán)境變量中,且這個(gè)示例中的代碼并沒有對(duì)WinRAR命令返回的錯(cuò)誤進(jìn)行詳細(xì)處理。
5.生成若干個(gè)txt并打包到zip中
代碼示例:
import java.io.*; import java.util.zip.*; public class GenerateTxtFilesAndZip { public static void main(String[] args) { String basePath = "path/to/your/directory"; // 更換為你想要保存文件的文件夾路徑 int fileCount = 10; // 要生成的文件數(shù)量 try { // 創(chuàng)建文件夾(如果不存在) File directory = new File(basePath); if (!directory.exists()) { directory.mkdirs(); } // 生成txt文件并寫入內(nèi)容 for (int i = 1; i <= fileCount; i++) { String fileName = "file" + i + ".txt"; String filePath = basePath + File.separator + fileName; String fileContent = "This is the content of " + fileName; try (BufferedWriter writer = new BufferedWriter(new FileWriter(filePath))) { writer.write(fileContent); } catch (IOException e) { e.printStackTrace(); } } // 打包成zip文件 String zipFileName = "output.zip"; byte[] buffer = new byte[1024]; FileOutputStream fos = new FileOutputStream(zipFileName); ZipOutputStream zos = new ZipOutputStream(fos); File dir = new File(basePath); File[] files = dir.listFiles(); if (files != null) { for (File file : files) { if (file.getName().endsWith(".txt")) { FileInputStream fis = new FileInputStream(file); zos.putNextEntry(new ZipEntry(file.getName())); int length; while ((length = fis.read(buffer)) > 0) { zos.write(buffer, 0, length); } zos.closeEntry(); fis.close(); } } } zos.close(); System.out.println("文件已成功打包成 " + zipFileName); } catch (IOException e) { e.printStackTrace(); } } }
請(qǐng)?zhí)鎿Qpath/to/your/directory
為你想要保存生成文件的實(shí)際文件夾路徑。這段代碼會(huì)在指定路徑下生成10個(gè).txt
文件,并將它們打包成一個(gè)名為output.zip
的ZIP文件。
附:Java實(shí)現(xiàn)zip、tar、tar.gz 打包壓縮解壓
package com.bj.drj; import cn.hutool.core.lang.Console; import org.apache.commons.compress.archivers.tar.TarArchiveEntry; import org.apache.commons.compress.archivers.tar.TarArchiveInputStream; import org.apache.commons.compress.archivers.tar.TarArchiveOutputStream; import org.apache.commons.compress.archivers.zip.ZipArchiveEntry; import org.apache.commons.compress.archivers.zip.ZipArchiveInputStream; import org.apache.commons.compress.archivers.zip.ZipArchiveOutputStream; import org.apache.commons.compress.compressors.gzip.GzipCompressorInputStream; import org.apache.commons.compress.compressors.gzip.GzipCompressorOutputStream; import org.apache.commons.io.IOUtils; import java.io.*; /** * @ClassName PackAndCompressionUtils * @Description: 解壓壓縮文件 * @Author drj * @Date 2021/9/18 * @Version V1.0 **/ public class PackAndCompressionUtils { private PackAndCompressionUtils() { } /** * 這個(gè)方法主要針對(duì)文件實(shí)現(xiàn)打包tar 也可以生成tar.gz 但是失去了gz 壓縮功能 只是現(xiàn)實(shí)了打包。 * * @param filesPathArray 需要打包的文件 * @param targetDirPath 生成tar 目錄 * @return * @throws Exception */ public static boolean tarPack(String[] filesPathArray, String targetDirPath) throws Exception { try (FileOutputStream fileOutputStream = new FileOutputStream(new File(targetDirPath)); BufferedOutputStream bufferedOutputStream = new BufferedOutputStream(fileOutputStream); TarArchiveOutputStream tarArchiveOutputStream = new TarArchiveOutputStream(bufferedOutputStream)) { for (String filePath : filesPathArray) { try (FileInputStream fileInputStream = new FileInputStream(new File(filePath))) { File file = new File(filePath); TarArchiveEntry tae = new TarArchiveEntry(file, file.getName()); tarArchiveOutputStream.putArchiveEntry(tae); IOUtils.copy(fileInputStream, tarArchiveOutputStream); tarArchiveOutputStream.closeArchiveEntry(); } catch (Exception e) { Console.error(e, "異常信息:{}", filePath); } } } catch (Exception e) { Console.error(e, "異常信息:{}", filesPathArray); } return true; } /** * 解壓打包文件 * * @param unPackFilePath * @param targetDirPath * @return * @throws Exception */ public static boolean tarUnpack(String unPackFilePath, String targetDirPath) throws Exception { try (FileInputStream fileInputStream = new FileInputStream(new File(unPackFilePath)); TarArchiveInputStream tarArchiveInputStream = new TarArchiveInputStream(fileInputStream)) { TarArchiveEntry tae = null; while ((tae = tarArchiveInputStream.getNextTarEntry()) != null) { String dir = targetDirPath + File.separator + tae.getName(); try (FileOutputStream fileOutputStream = new FileOutputStream(new File(dir)); BufferedOutputStream bufferedOutputStream = new BufferedOutputStream(fileOutputStream)) { IOUtils.copy(tarArchiveInputStream, bufferedOutputStream); } catch (Exception ex) { Console.error(ex, "異常文件:{}", dir); } } } catch (Exception ex) { Console.error(ex, "異常文件:{}", unPackFilePath); } return true; } /** * gzip壓縮文件 后綴是.gz * * @param filesPathArray * @param targetDirPath * @return * @throws IOException */ public static boolean gzipCompress(String[] filesPathArray, String targetDirPath) throws IOException { try (OutputStream outputStream = new FileOutputStream(new File(targetDirPath)); GzipCompressorOutputStream gzipCompressorOutputStream = new GzipCompressorOutputStream(outputStream)) { for (String filePath : filesPathArray) { try (InputStream inputStream = new FileInputStream(new File(filePath));) { TarArchiveOutputStream tarArchiveOutputStream = new TarArchiveOutputStream(gzipCompressorOutputStream); File file = new File(filePath); TarArchiveEntry archiveEntry = new TarArchiveEntry(file, file.getName()); tarArchiveOutputStream.putArchiveEntry(archiveEntry); IOUtils.copy(inputStream, tarArchiveOutputStream); tarArchiveOutputStream.closeArchiveEntry(); } catch (Exception ex) { Console.error(ex, "異常文件:{}", filePath); } } } catch (Exception ex) { Console.error(ex, "異常文件:{}", filesPathArray); } return true; } /** * 針對(duì)gz包 進(jìn)行解壓 * * @param sourceDir * @param targetDirPath */ public static boolean gzipDeCompress(String sourceDir, String targetDirPath) { try ( FileInputStream fileInputStream = new FileInputStream(sourceDir); GzipCompressorInputStream gzipCompressorInputStream = new GzipCompressorInputStream(fileInputStream); TarArchiveInputStream tarArchiveInputStream = new TarArchiveInputStream(gzipCompressorInputStream); ) { TarArchiveEntry tarArchiveEntry = null; while ((tarArchiveEntry = tarArchiveInputStream.getNextTarEntry()) != null) { String dir = targetDirPath + File.separator + tarArchiveEntry.getName(); try (FileOutputStream fileOutputStream = new FileOutputStream(new File(dir))) { IOUtils.copy(tarArchiveInputStream, fileOutputStream); } catch (Exception ex) { Console.error(ex, "異常文件路徑:{}", sourceDir); } } } catch (Exception ex) { Console.error(ex, "異常文件路徑:{}", sourceDir); } return true; } /** * 對(duì)文件進(jìn)行zip打包處理 * * @param filesPathArray * @param targetDirPath * @return * @throws Exception */ public static boolean zipCompress(String[] filesPathArray, String targetDirPath) throws Exception { try (FileOutputStream fileOutputStream = new FileOutputStream(new File(targetDirPath)); ZipArchiveOutputStream zipArchiveOutputStream = new ZipArchiveOutputStream(fileOutputStream)) { for (String filePath : filesPathArray) { try (FileInputStream fileInputStream = new FileInputStream(new File(filePath))) { File file = new File(filePath); ZipArchiveEntry zae = new ZipArchiveEntry(file, file.getName()); zipArchiveOutputStream.putArchiveEntry(zae); IOUtils.copy(fileInputStream, zipArchiveOutputStream); zipArchiveOutputStream.closeArchiveEntry(); } catch (Exception ex) { Console.error(ex, "異常文件路徑:{}", filePath); } } } catch (Exception ex) { Console.error(ex, "異常文件路徑:{}", filesPathArray); } return true; } /** * 解壓zip 文件 * * @param decompressFilePath * @param targetDirPath * @return * @throws Exception */ public static boolean zipDecompress(String decompressFilePath, String targetDirPath) throws Exception { try (FileInputStream fileInputStream = new FileInputStream(new File(decompressFilePath)); ZipArchiveInputStream zipArchiveInputStream = new ZipArchiveInputStream(fileInputStream)) { ZipArchiveEntry zae = null; while ((zae = zipArchiveInputStream.getNextZipEntry()) != null) { String dir = targetDirPath + File.separator + zae.getName(); try (FileOutputStream fileOutputStream = new FileOutputStream(new File(dir))) { IOUtils.copy(zipArchiveInputStream, fileOutputStream); } catch (Exception ex) { Console.error(ex, "異常文件路徑:{}", dir); } } } catch (Exception ex) { Console.error(ex, "異常文件路徑:{}", decompressFilePath); } return true; } }
單元測(cè)試
String[] filesPathArray = new String[]{"D:\\core\\a.txt", "D:\\core\\b.txt"}; String[] fileTarPath = new String[]{"D:\\core\\tarcompress.tar"}; String compressTarTargetDirPath = "D:\\core\\tarcompress.tar.gz"; String compressZipTargetDirPath = "D:\\core\\tarcompress.zip"; String compressGzTargetDirPath = "D:\\core\\tarcompress3.gz"; String compressGzTargetDirPath4 = "D:\\core\\tarcompress4.gz"; String deCompressDirPath = "D:\\core"; @Test public void testTarPack() throws Exception { boolean b = PackAndCompressionUtils.tarPack(filesPathArray, compressTarTargetDirPath); Assert.assertTrue(b); } @Test public void testTarUnpack() throws Exception { boolean b = PackAndCompressionUtils.tarUnpack(compressGzTargetDirPath, deCompressDirPath); Assert.assertTrue(b); } @Test public void testZipCompress() throws Exception { boolean b = PackAndCompressionUtils.zipCompress(filesPathArray, compressZipTargetDirPath); Assert.assertTrue(b); } @Test public void testZipDeCompress() throws Exception { boolean b = PackAndCompressionUtils.zipDecompress(compressZipTargetDirPath, deCompressDirPath); Assert.assertTrue(b); } @Test public void test() throws Exception { MyUnTarGzUtil.unTarGz(compressGzTargetDirPath,deCompressDirPath); } @Test public void testGzCompress() throws Exception { boolean b = PackAndCompressionUtils.gzipCompress(filesPathArray, compressGzTargetDirPath4); Assert.assertTrue(b); } @Test public void testGzDeCompress() throws Exception { boolean b = PackAndCompressionUtils.gzipDeCompress(compressTarTargetDirPath, deCompressDirPath); Assert.assertTrue(b); }
總結(jié)
到此這篇關(guān)于Java打成各種壓縮包的文章就介紹到這了,更多相關(guān)Java打成壓縮包內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
java使用EasyExcel導(dǎo)入導(dǎo)出excel
導(dǎo)入導(dǎo)出excel數(shù)據(jù)是常見的需求,今天就來看一下Java基于EasyExcel實(shí)現(xiàn)這個(gè)功能,感興趣的朋友可以了解下2021-05-05Maven項(xiàng)目改為spring boot項(xiàng)目的方法圖解
這篇文章主要介紹了Maven項(xiàng)目改為spring boot項(xiàng)目的方法圖解 ,本文給大家介紹的非常詳細(xì),具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2018-09-09Mybatis-plus自動(dòng)填充不生效或自動(dòng)填充數(shù)據(jù)為null原因及解決方案
本文主要介紹了Mybatis-plus自動(dòng)填充不生效或自動(dòng)填充數(shù)據(jù)為null原因及解決方案,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2022-05-05詳解spring boot應(yīng)用啟動(dòng)原理分析
這篇文章主要介紹了詳解spring boot應(yīng)用啟動(dòng)原理分析,小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過來看看吧2018-06-06使用Netty快速實(shí)現(xiàn)一個(gè)群聊功能的示例詳解
這篇文章主要為大家詳細(xì)介紹了如何利用?Netty?框架開發(fā)一個(gè)?WebSocket?服務(wù)端,從而實(shí)現(xiàn)一個(gè)簡(jiǎn)單的在線聊天功能,感興趣的小伙伴可以了解下2023-11-11Hadoop源碼分析六啟動(dòng)文件namenode原理詳解
本篇是Hadoop源碼分析系列文章第六篇,主要介紹Hadoop中的啟動(dòng)文件namenode,后續(xù)本系列文章會(huì)持續(xù)更新,有需要的朋友可以借鑒參考下2021-09-09mybatis批量update時(shí)報(bào)錯(cuò)multi-statement not allow的問題
這篇文章主要介紹了mybatis批量update時(shí)報(bào)錯(cuò)multi-statement not allow的問題及解決方案,具有很好的參考價(jià)值,希望對(duì)大家有所幫助,如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2023-10-10Intellij IDEA 斷點(diǎn)不可用報(bào)錯(cuò) No executable 
這篇文章主要介紹了Intellij IDEA 斷點(diǎn)不可用報(bào)錯(cuò) No executable code found問題及解決方案,具有很好的參考價(jià)值,希望對(duì)大家有所幫助,如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2023-10-10