How to Create Zip File in Java?In Java, working with zip file is not the same as working with word file or text file. In the context of zip file Java provides different ways to create zip or compressed or archive file. In this section, we will learn how to create zip file in Java. The necessary classes and interfaces that are required to create a zip file are defined in java.util.zip package. The package does not only provide classes for ZIP format but also provides classes for the GZIP format. The package also provides the classes to read from and write to the zip file. Using java.util.Zip PackageBefore creating the Java program, first we need to download the apache common compress JAR file. Now create a Java project and add this JAR file to the project. Copy the following Java program and paste it in the class file that you have created. CreateZipFile1.java Let's compile and run the above program. Output: We observe that a zip file with the specified name is created. Let's open the zip file and see the specified file added to zip file or not. Zipping Multiple FilesZippingMultipleFiles.java Output: Zipping a DirectoryCreate a zip of a directory is a bit different form the above approach. Java provides two way to zip a directory:
Using Files.walkFileTree()
Syntax: It accepts two parameters: start: It denotes the starting file. visitor: Th file visitor to invoke each file. The FileVisitor is an interface that acts as an argument for the method. To walk over a file tree, we need to implement a FileVisitor interface. It specifies the required behavior at key points in the traversal process that are:
Let's implement the logic to create a zip file for a directory. ZippingDirectory.java Output: Next TopicJava Dot Operator |
We provides tutorials and interview questions of all technology like java tutorial, android, java frameworks
G-13, 2nd Floor, Sec-3, Noida, UP, 201301, India