Java zip file windows

Java zip file windows

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

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

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

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

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

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

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

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

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

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

Zipping and Unzipping in Java

Last modified: November 20, 2020

Get started with Spring 5 and Spring Boot 2, through the Learn Spring course:

If you have a few years of experience in the Java ecosystem, and you’re interested in sharing that experience with the community (and getting paid for your work of course), have a look at the «Write for Us» page. Cheers, Eugen

1. Overview

In this quick tutorial, we’ll discuss 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

Let’s first have a look at a simple operation – zipping a single file.

For our example here we’ll zip a file named test1.txt into an archived named compressed.zip.

We’ll of course first access the file from disk – let’s have a look:

3. Zip Multiple Files

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

4. Zip a Directory

Now, let’s discuss how to zip an entire directory. We will directory zipTest into dirCompressed.zip :

  • To zip sub-directories, we iterate through them recursively.
  • Every time we find a directory, we append its name to the descendants ZipEntry name to save the hierarchy.
  • We also create a directory entry for every empty directory
Читайте также:  Read only file system linux ��� ��������� windows 10

5. Unzip an Archive

Let’s now unzip an archive and extract its contents.

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

Let’s have a look:

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:

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

Another key point can be seen in the newFile() method:

This method guards against writing files to the file system outside of the target folder. This vulnerability is called Zip Slip and you can read more about it here.

6. Conclusion

This tutorial illustrated how we can use Java libraries for the operations of zipping and unzipping files.

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

How to create Zip file in Java

This article shows a few examples to zip a single file and a whole directory (including sub-files and subdirectories).

  1. Zip a file – java.util.zip
  2. Zip a file – Files.copy to Zip FileSystems
  3. Zip a file on demand (without write to disk)
  4. Zip a folder – File tree and java.util.zip
  5. Zip a folder – File tree and Files.copy to Zip FileSystems
  6. zipj4 library

Java 7 introduced the Zip File System Provider, combines with Files.copy , we can copy the file attributes into the zip file easily (see example 4).

1. Zip a single file – java.util.zip

1.1 This Java example uses java.util.zip.ZipOutputStream to zip a single file.

2. Zip a single file – FileSystems

2.1 This example uses the Java 7 NIO FileSystems.newFileSystem to create a zip file and Files.copy to copy the files into the zip path.

3. Zip a single file on demand

This example uses ByteArrayInputStream to directly create some bytes on demand and save it into the zip file without saving or writing the data into the local file system.

4. Zip a folder or directory – java.util.zip

4.1 Review a directory that includes some sub-files and subdirectories.

4.2 This Java example uses FileVisitor to walk a file tree and ZipOutputStream to zip everything manually, including sub-files and subdirectories, but ignore symbolic links and file attributes.

The above example creates the zip file at the current working directory, and we didn’t copy the file attributes (review the file created date and time).

5. Zip a folder or directory – FileSystems

5.1 This example uses the same FileVisitor to walk the file tree. Still, this time we use FileSystems URI to create the zip file, and Files.copy to copy the files into the zip path, including the file attributes, but ignore the symbolic link.

6. Zip file – zip4j

The zip4j is a popular zip library in Java; it has many advanced features like a password-protected zip file, split zip file, AES encryption, etc. Please visit the zip4j github for further documentation and usages.

Читайте также:  Что нужно устанавливать после установки windows

Here’s are some common usages to zip files and folder.

Download Source Code

References

mkyong

Is there a way to create multiple txt files (without creating the txt files locally) which will be zipped and then send back to the user as a zipped folder? I have created a web service which enables the user to download a zipped folder with specific txt files. But in order to do that, I have to create the txt files locally -> zip them -> delete the txt files from the local storage.

When the service is deployed, I am not allowed to create files on the server. I saw that some people mentioned to create the files in-memory but there are risks. There is a case that I might run out of memory.

The above method is used to create and return a File. I have a List which contains all the txt files. I iterate the list and add the files into ZipOutputStream etc.

What do you think I should do? Is there an example which I can see?

Java ZIP — how to unzip folder?

Is there any sample code, how to particaly unzip folder from ZIP into my desired directory? I have read all files from folder «FOLDER» into byte array, how do I recreate from its file structure?

8 Answers 8

I am not sure what do you mean by particaly? Do you mean do it yourself without of API help?

In the case you don’t mind using some opensource library, there is a cool API for that out there called zip4J

It is easy to use and I think there is good feedback about it. See this example:

If the files you want to unzip have passwords, you can try this:

I hope this is useful.

Here is the code I’m using. Change BUFFER_SIZE for your needs.

A most concise, library-free, Java 7+ variant:

The createDirectories is needed in both branches because zip files not always contain all the parent directories as a separate entries, but might contain them only to represent empty directories.

The code addresses the ZIP-slip vulnerability, it fails if some ZIP entry would go outside of the targetDir . Such ZIPs are not created using the usual tools and are very likely hand-crafted to exploit the vulnerability.

Same can be achieved using Ant Compress library. It will preserve the folder structure.

Here’s an easy solution which follows more modern conventions. You may want to change the buffer size to be smaller if you’re unzipping larger files. This is so you don’t keep all of the files info in-memory.

This is the code I used to unzip a zip file with multiple directories. No external libraries used.

Here is more «modern» complete code based on this post but refactored (and using Lombok ):

Appending files to a zip file with Java

I am currently extracting the contents of a war file and then adding some new files to the directory structure and then creating a new war file.

This is all done programatically from Java — but I am wondering if it wouldn’t be more efficient to copy the war file and then just append the files — then I wouldn’t have to wait so long as the war expands and then has to be compressed again.

Читайте также:  Создание шаблона microsoft windows

I can’t seem to find a way to do this in the documentation though or any online examples.

Anyone can give some tips or pointers?

TrueZip as mentioned in one of the answers seems to be a very good java library to append to a zip file (despite other answers that say it is not possible to do this).

Anyone have experience or feedback on TrueZip or can recommend other similar libaries?

13 Answers 13

In Java 7 we got Zip File System that allows adding and changing files in zip (jar, war) without manual repackaging.

We can directly write to files inside zip files as in the following example.

As others mentioned, it’s not possible to append content to an existing zip (or war). However, it’s possible to create a new zip on the fly without temporarily writing extracted content to disk. It’s hard to guess how much faster this will be, but it’s the fastest you can get (at least as far as I know) with standard Java. As mentioned by Carlos Tasada, SevenZipJBindings might squeeze out you some extra seconds, but porting this approach to SevenZipJBindings will still be faster than using temporary files with the same library.

Here’s some code that writes the contents of an existing zip (war.zip) and appends an extra file (answer.txt) to a new zip (append.zip). All it takes is Java 5 or later, no extra libraries needed.

I had a similar requirement sometime back — but it was for reading and writing zip archives (.war format should be similar). I tried doing it with the existing Java Zip streams but found the writing part cumbersome — especially when directories where involved.

I’ll recommend you to try out the TrueZIP (open source — apache style licensed) library that exposes any archive as a virtual file system into which you can read and write like a normal filesystem. It worked like a charm for me and greatly simplified my development.

You could use this bit of code I wrote

I don’t know of a Java library that does what you describe. But what you described is practical. You can do it in .NET, using DotNetZip.

Michael Krauklis is correct that you cannot simply «append» data to a war file or zip file, but it is not because there is an «end of file» indication, strictly speaking, in a war file. It is because the war (zip) format includes a directory, which is normally present at the end of the file, that contains metadata for the various entries in the war file. Naively appending to a war file results in no update to the directory, and so you just have a war file with junk appended to it.

What’s necessary is an intelligent class that understands the format, and can read+update a war file or zip file, including the directory as appropriate. DotNetZip does this, without uncompressing/recompressing the unchanged entries, just as you described or desired.

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