Java提供了多種解壓縮和壓縮文件的方式,其中gzip和zip是比較常用的格式。
對于gzip壓縮文件,我們可以使用GZIPInputStream來進行解壓:
public static void decompressGzip(File input, File output) throws IOException { try (GZIPInputStream in = new GZIPInputStream(new FileInputStream(input)); OutputStream out = new FileOutputStream(output)) { byte[] buffer = new byte[1024]; int len; while ((len = in.read(buffer)) >0) { out.write(buffer, 0, len); } } }
對于zip壓縮文件,我們可以使用ZipInputStream和ZipEntry來進行解壓,如下所示:
public static void decompressZip(File input, File outputDir) throws IOException { try (ZipInputStream in = new ZipInputStream(new FileInputStream(input))) { byte[] buffer = new byte[1024]; ZipEntry entry; while ((entry = in.getNextEntry()) != null) { File destFile = new File(outputDir, entry.getName()); if (entry.isDirectory()) { destFile.mkdirs(); } else { try (OutputStream out = new FileOutputStream(destFile)) { int len; while ((len = in.read(buffer)) >0) { out.write(buffer, 0, len); } } } } } }
以上代碼中的try-with-resources語句確保資源會在用完后自動關閉,而不用顯式地調用close方法。