Java zip archive library

Package java.util.zip

Provides classes for reading and writing the standard ZIP and GZIP file formats. Also includes classes for compressing and decompressing data using the DEFLATE compression algorithm, which is used by the ZIP and GZIP file formats. Additionally, there are utility classes for computing the CRC-32, CRC-32C and Adler-32 checksums of arbitrary input streams.

Package Specification

  • Info-ZIP Application Note 970311 — a detailed description of the Info-ZIP format upon which the java.util.zip classes are based.
  • An implementation may optionally support the ZIP64(tm) format extensions defined by thePKWARE ZIP File Format Specification. The ZIP64(tm) format extensions are used to overcome the size limitations of the original ZIP format.
  • APPENDIX D ofPKWARE ZIP File Format Specification — Language Encoding Flag to encode ZIP entry filename and comment fields using UTF-8.
  • ZLIB Compressed Data Format Specification version 3.3(pdf) (RFC 1950)
  • DEFLATE Compressed Data Format Specification version 1.3(pdf) (RFC 1951)
  • GZIP file format specification version 4.3(pdf) (RFC 1952)
  • CRC-32 checksum is described in RFC 1952 (above)
  • CRC-32C checksum is described in Internet Small Computer Systems Interface (iSCSI)(pdf) (RFC 3720)
  • Adler-32 checksum is described in RFC 1950 (above)

Contains the collections framework, some internationalization support classes, a service loader, properties, random number generation, string parsing and scanning classes, base64 encoding and decoding, a bit array, and several miscellaneous utility classes.

Читайте также:  The set method in java

Источник

Zipping and Unzipping in Java

announcement - icon

The Kubernetes ecosystem is huge and quite complex, so it’s easy to forget about costs when trying out all of the exciting tools.

To avoid overspending on your Kubernetes cluster, definitely have a look at the free K8s cost monitoring tool from the automation platform CAST AI. You can view your costs in real time, allocate them, calculate burn rates for projects, spot anomalies or spikes, and get insightful reports you can share with your team.

Connect your cluster and start monitoring your K8s costs right away:

We rely on other people’s code in our own work. Every day.

It might be the language you’re writing in, the framework you’re building on, or some esoteric piece of software that does one thing so well you never found the need to implement it yourself.

The problem is, of course, when things fall apart in production — debugging the implementation of a 3rd party library you have no intimate knowledge of is, to say the least, tricky.

Lightrun is a new kind of debugger.

It’s one geared specifically towards real-life production environments. Using Lightrun, you can drill down into running applications, including 3rd party dependencies, with real-time logs, snapshots, and metrics.

Learn more in this quick, 5-minute Lightrun tutorial:

announcement - icon

Slow MySQL query performance is all too common. Of course it is. A good way to go is, naturally, a dedicated profiler that actually understands the ins and outs of MySQL.

The Jet Profiler was built for MySQL only, so it can do things like real-time query performance, focus on most used tables or most frequent queries, quickly identify performance issues and basically help you optimize your queries.

Critically, it has very minimal impact on your server’s performance, with most of the profiling work done separately — so it needs no server changes, agents or separate services.

Basically, you install the desktop application, connect to your MySQL server, hit the record button, and you’ll have results within minutes:

announcement - icon

DbSchema is a super-flexible database designer, which can take you from designing the DB with your team all the way to safely deploying the schema.

The way it does all of that is by using a design model, a database-independent image of the schema, which can be shared in a team using GIT and compared or deployed on to any database.

And, of course, it can be heavily visual, allowing you to interact with the database using diagrams, visually compose queries, explore the data, generate random data, import data or build HTML5 database reports.

announcement - icon

The Kubernetes ecosystem is huge and quite complex, so it’s easy to forget about costs when trying out all of the exciting tools.

To avoid overspending on your Kubernetes cluster, definitely have a look at the free K8s cost monitoring tool from the automation platform CAST AI. You can view your costs in real time, allocate them, calculate burn rates for projects, spot anomalies or spikes, and get insightful reports you can share with your team.

Connect your cluster and start monitoring your K8s costs right away:

We’re looking for a new Java technical editor to help review new articles for the site.

1. Overview

In this quick tutorial, we’ll learn how to zip a file into an archive and how to unzip the archive, all using core libraries provided by Java.

These core libraries are part of the java.util.zip package, where we can find all zipping- and unzipping-related utilities.

2. Zip a File

First, let’s look at a simple operation, zipping a single file.

For example, we’ll zip a file named test1.txt into an archive named compressed.zip.

Of course, we’ll first access the file from a disk:

public class ZipFile < public static void main(String[] args) throws IOException < String sourceFile = "test1.txt"; FileOutputStream fos = new FileOutputStream("compressed.zip"); ZipOutputStream zipOut = new ZipOutputStream(fos); File fileToZip = new File(sourceFile); FileInputStream fis = new FileInputStream(fileToZip); ZipEntry zipEntry = new ZipEntry(fileToZip.getName()); zipOut.putNextEntry(zipEntry); byte[] bytes = new byte[1024]; int length; while((length = fis.read(bytes)) >= 0) < zipOut.write(bytes, 0, length); >zipOut.close(); fis.close(); fos.close(); > >

3. Zip Multiple Files

Next, let’s see how to zip multiple files into one zip file. We’ll compress test1.txt and test2.txt into multiCompressed.zip:

public class ZipMultipleFiles < public static void main(String[] args) throws IOException < String file1 = "src/main/resources/zipTest/test1.txt"; String file2 = "src/main/resources/zipTest/test2.txt"; final ListsrcFiles = Arrays.asList(file1, file2); final FileOutputStream fos = new FileOutputStream(Paths.get(file1).getParent().toAbsolutePath() + "/compressed.zip"); ZipOutputStream zipOut = new ZipOutputStream(fos); for (String srcFile : srcFiles) < File fileToZip = new File(srcFile); FileInputStream fis = new FileInputStream(fileToZip); ZipEntry zipEntry = new ZipEntry(fileToZip.getName()); zipOut.putNextEntry(zipEntry); byte[] bytes = new byte[1024]; int length; while((length = fis.read(bytes)) >= 0) < zipOut.write(bytes, 0, length); >fis.close(); > zipOut.close(); fos.close(); > >

4. Zip a Directory

Now, let’s discuss how to zip an entire directory. Here, we’ll compress the zipTest folder into the dirCompressed.zip file:

public class ZipDirectory < public static void main(String[] args) throws IOException < String sourceFile = "zipTest"; FileOutputStream fos = new FileOutputStream("dirCompressed.zip"); ZipOutputStream zipOut = new ZipOutputStream(fos); File fileToZip = new File(sourceFile); zipFile(fileToZip, fileToZip.getName(), zipOut); zipOut.close(); fos.close(); >private static void zipFile(File fileToZip, String fileName, ZipOutputStream zipOut) throws IOException < if (fileToZip.isHidden()) < return; >if (fileToZip.isDirectory()) < if (fileName.endsWith("/")) < zipOut.putNextEntry(new ZipEntry(fileName)); zipOut.closeEntry(); >else < zipOut.putNextEntry(new ZipEntry(fileName + "/")); zipOut.closeEntry(); >File[] children = fileToZip.listFiles(); for (File childFile : children) < zipFile(childFile, fileName + "/" + childFile.getName(), zipOut); >return; > FileInputStream fis = new FileInputStream(fileToZip); ZipEntry zipEntry = new ZipEntry(fileName); zipOut.putNextEntry(zipEntry); byte[] bytes = new byte[1024]; int length; while ((length = fis.read(bytes)) >= 0) < zipOut.write(bytes, 0, length); >fis.close(); > >
  • To zip sub-directories, we iterate through them recursively.
  • Every time we find a directory, we append its name to the descendant’s ZipEntry name to save the hierarchy.
  • We also create a directory entry for every empty directory.

5. Append New Files to Zip File

Next, we’ll add a single file to an existing zip file. For example, let’s add file3.txt into compressed.zip:

String file3 = "src/main/resources/zipTest/file3.txt"; Map env = new HashMap<>(); env.put("create", "true"); Path path = Paths.get(Paths.get(file3).getParent() + "/compressed.zip"); URI uri = URI.create("jar:" + path.toUri()); try (FileSystem fs = FileSystems.newFileSystem(uri, env))

In short, we mounted the zip file using .newFileSystem() provided by the FileSystems class, which has been available since JDK 1.7. Then, we created a newFile3.txt inside the compressed folder and added all the contents from file3.txt.

6. Unzip an Archive

Now, let’s unzip an archive and extract its contents.

For this example, we’ll unzip compressed.zip into a new folder named unzipTest:

public class UnzipFile < public static void main(String[] args) throws IOException < String fileZip = "src/main/resources/unzipTest/compressed.zip"; File destDir = new File("src/main/resources/unzipTest"); byte[] buffer = new byte[1024]; ZipInputStream zis = new ZipInputStream(new FileInputStream(fileZip)); ZipEntry zipEntry = zis.getNextEntry(); while (zipEntry != null) < // . >zis.closeEntry(); zis.close(); > >

Inside the while loop, we’ll iterate through each ZipEntry and first check if it’s a directory. If it is, then we’ll create the directory using the mkdirs() method; otherwise, we’ll continue with creating the file:

while (zipEntry != null) < File newFile = newFile(destDir, zipEntry); if (zipEntry.isDirectory()) < if (!newFile.isDirectory() && !newFile.mkdirs()) < throw new IOException("Failed to create directory " + newFile); >> else < // fix for Windows-created archives File parent = newFile.getParentFile(); if (!parent.isDirectory() && !parent.mkdirs()) < throw new IOException("Failed to create directory " + parent); >// write file content FileOutputStream fos = new FileOutputStream(newFile); int len; while ((len = zis.read(buffer)) > 0) < fos.write(buffer, 0, len); >fos.close(); > zipEntry = zis.getNextEntry(); >

One note here is that on the else branch, we’re also checking if the file’s parent directory exists. This is necessary for archives created on Windows, where the root directories don’t have a corresponding entry in the zip file.

Another critical point is in the newFile() method:

public static File newFile(File destinationDir, ZipEntry zipEntry) throws IOException < File destFile = new File(destinationDir, zipEntry.getName()); String destDirPath = destinationDir.getCanonicalPath(); String destFilePath = destFile.getCanonicalPath(); if (!destFilePath.startsWith(destDirPath + File.separator)) < throw new IOException("Entry is outside of the target dir: " + zipEntry.getName()); >return destFile; >

The newFile() method guards against writing files to the file system outside the target folder. This vulnerability is called Zip Slip.

7. Conclusion

In this article, we illustrated how to use Java libraries for zipping and unzipping files.

The implementation of these examples can be found over on GitHub.

announcement - icon

Slow MySQL query performance is all too common. Of course it is. A good way to go is, naturally, a dedicated profiler that actually understands the ins and outs of MySQL.

The Jet Profiler was built for MySQL only, so it can do things like real-time query performance, focus on most used tables or most frequent queries, quickly identify performance issues and basically help you optimize your queries.

Critically, it has very minimal impact on your server’s performance, with most of the profiling work done separately — so it needs no server changes, agents or separate services.

Basically, you install the desktop application, connect to your MySQL server, hit the record button, and you’ll have results within minutes:

Источник

Java zip archive library

Кроме общего функционала для работы с файлами Java предоставляет функциональность для работы с таким видом файлов как zip-архивы. Для этого в пакете java.util.zip определены два класса — ZipInputStream и ZipOutputStream

ZipOutputStream. Запись архивов

Для создания архива используется класс ZipOutputStream. Для создания объекта ZipOutputStream в его конструктор передается поток вывода:

ZipOutputStream(OutputStream out)

Для записи файлов в архив для каждого файла создается объект ZipEntry , в конструктор которого передается имя архивируемого файла. А чтобы добавить каждый объект ZipEntry в архив, применяется метод putNextEntry() .

import java.io.*; import java.util.zip.*; public class Program < public static void main(String[] args) < String filename = "notes.txt"; try(ZipOutputStream zout = new ZipOutputStream(new FileOutputStream("output.zip")); FileInputStream fis= new FileInputStream(filename);) < ZipEntry entry1=new ZipEntry("notes.txt"); zout.putNextEntry(entry1); // считываем содержимое файла в массив byte byte[] buffer = new byte[fis.available()]; fis.read(buffer); // добавляем содержимое к архиву zout.write(buffer); // закрываем текущую запись для новой записи zout.closeEntry(); >catch(Exception ex) < System.out.println(ex.getMessage()); >> >

После добавления объекта ZipEntry в поток нам также надо добавить в него и содержимое файла. Для этого используется метод write, записывающий в поток массив байтов: zout.write(buffer); . В конце надо закрыть ZipEntry с помощью метода closeEntry() . После этого можно добавлять в архив новые файлы — в этом случае все вышеописанные действия для каждого нового файла повторяются.

Чтение архивов. ZipInputStream

Для чтения архивов применяется класс ZipInputStream . В конструкторе он принимает поток, указывающий на zip-архив:

ZipInputStream(InputStream in)

Для считывания файлов из архива ZipInputStream использует метод getNextEntry() , который возвращает объект ZipEntry . Объект ZipEntry представляет отдельную запись в zip-архиве. Например, считаем какой-нибудь архив:

import java.io.*; import java.util.zip.*; public class Program < public static void main(String[] args) < try(ZipInputStream zin = new ZipInputStream(new FileInputStream("output.zip"))) < ZipEntry entry; String name; while((entry=zin.getNextEntry())!=null)< name = entry.getName(); // получим название файла System.out.printf("File name: %s \n", name); // распаковка FileOutputStream fout = new FileOutputStream("new" + name); for (int c = zin.read(); c != -1; c = zin.read()) < fout.write(c); >fout.flush(); zin.closeEntry(); fout.close(); > > catch(Exception ex) < System.out.println(ex.getMessage()); >> >

ZipInputStream в конструкторе получает ссылку на поток ввода. И затем в цикле выводятся все файлы и их размер в байтах, которые находятся в данном архиве.

Затем данные извлекаются из архива и сохраняются в новые файлы, которые находятся в той же папке и которые начинаются с «new».

Источник

Оцените статью