Java 17 Recipes
Download 3.2 Mb. Pdf ko'rish
|
Java 17 Recipes
8-12. Uncompressing Files
Problem Your application has the requirement to decompress and extract files from a compressed .zip file. Solution Using the java.util.zip package, you can open a .zip file and iterate through its entries. While traversing the entries, directories can be created for directory entries. The following lines of code demonstrate how to perform the decompress and file iteration technique, as described. ChApTer 8 InpuT And OuTpuT 326 public class Ch_8_12_ZipExample { public static void main(String[] args) { Ch_8_12_ZipExample example = new Ch_8_12_ZipExample(); example.start(); } private void start() { ZipFile file = null; try { file = new ZipFile("file.zip"); FileSystem fileSystem = FileSystems.getDefault(); Enumeration extends ZipEntry> entries = file.entries(); String uncompressedDirectory = "uncompressed/"; Files.createDirectory(fileSystem.getPath(uncompressedDirectory)); while (entries.hasMoreElements()) { ZipEntry entry = entries.nextElement(); if (entry.isDirectory()) { System.out.println("Creating Directory:" + uncompressedDirectory + entry.getName()); Files.createDirectories(fileSystem. getPath(uncompressedDirectory + entry.getName())); } else { InputStream is = file.getInputStream(entry); System.out.println("File :" + entry.getName()); BufferedInputStream bis = new BufferedInputStream(is); String uncompressedFileName = uncompressedDirectory + entry. getName(); Path uncompressedFilePath = fileSystem. getPath(uncompressedFileName); Files.createFile(uncompressedFilePath); try (FileOutputStream fileOutput = new FileOutputStream(uncompr essedFileName)) { ChApTer 8 InpuT And OuTpuT 327 while (bis.available() > 0) { fileOutput.write(bis.read()); } } System.out.println("Written :" + entry.getName()); } } } catch (IOException e) { e.printStackTrace(); } } Download 3.2 Mb. Do'stlaringiz bilan baham: |
Ma'lumotlar bazasi mualliflik huquqi bilan himoyalangan ©fayllar.org 2024
ma'muriyatiga murojaat qiling
ma'muriyatiga murojaat qiling