ArtsAutosBooksBusinessEducationEntertainmentFamilyFashionFoodGamesGenderHealthHolidaysHomeHubPagesPersonal FinancePetsPoliticsReligionSportsTechnologyTravel

Java Examples - Creating Zip Archieve File Using "FileSystem" Class

Updated on September 5, 2018
sirama profile image

I am a software engineer. I have been working with C++, MFC, and .net technologies for 15 years. I like playing video games & reading books.

4 out of 5 stars from 1 rating of This Article

1. Introduction to Java FileSystem

In this example, First, we are going to create a Zip File and then add two text files to the Zip content. While article progress, we will learn what is FileSystem and how a copy can be performed between two File Systems.

The “Default File System” is the one in which windows organizes the file in Directory Tree structure. In our example we are going to create New file system for “Zip Cabinet Achieve” and then we will be coping the file from Default File System to Zip File System. OK. We will get more picture when we are progressing through the Example.

2. Creating Zip file using Java

Before we move into the Example, import the required packages. The package inclusion is given below:

import java.io.IOException;
import java.net.URISyntaxException;
import java.nio.file.*;
import java.util.HashMap;
import java.util.Map;
import java.net.URI;

Now look at the code example given below which creates a zip file and places that in the applications working directory. In this case, we will be creating a zip file in the same file location where this java program exists.

Creating an Empty Zip file in Java
Creating an Empty Zip file in Java | Source

2.1 Creating ZIP Properties Using Java Map

In the above code, first, we are creating the Java Map class instance called zipSysProps (Marked as 1). A Map is a "Key Value Pair" and value can be retrieved when a key is given. In our case, the Map zipSysProps populated with only one key pair by calling the "put() method" of the Map class. The key is “create” and the value is “true”. The Map that we created will acts as Zip File property which is required while we make a call to the Zip creation API.

2.2 Unique Resource Identifier (URI) Zip

OK. Zip property is ready. Where do we want to create the Zip file? What is the name of the file? This information can be given to Zip creation API through the URI instance. An URI is “Unique Resource Identifier” which is widely used in java to locate the resource. A resource can be a Web URL, A Network Socket, A Remote Java Object etc. In our case, the resource is a Zip file. The path to our zip file is retrieved by making call to the “get()” method of the “Paths” factory class. This get method returns “WindowsPath” object (Represented internally by java) and it is stored in the Path interface. Note that the path includes the Zip file name as well which is passed as parameter to the get() method (Marked as 2). Once we have path to ZIP File, we are creating the URI object and storing that in zip_uri (Marked as 3). The first parameter to the URI constructor defines the URI type. In our case, it is Zip Content (jar scheme) and the second parameter tells path to the Zip location.

2.3 Creating Java Zip File System by making use of URI

The zip in java acts as a separate file system called “Zip File System” and it can have its own directory structure in it. Using the “FileSystems” factory class, we are making call to the “newFileSystem()” method to create the Zip file. The first parameter is URI which tells Zip File location in “Windows File System” and second parameter is the property of the Zip passed as Map. The property asks to create the Zip file in the path specified by the URI. The method return is stored in the FileSystem reference ZipFileSystem which we can use later to add the files to it.

If you run the program at this stage, you will get an empty Zip file in the folder in which the Main class resides.

3. Adding Files to Zip Content in Java

In the previous section, we created our Zip file. But, the zip file does not have anything in it. Now, let us place two text files inside the already create Zip content. The text file creation is not done through java code. So, create two text files named SampleDoc-01.txt and SampleDoc-02.txt. Add some text contents in both the files and save both. Now, have a look at the below code:

Adding Files to Zip File System of Java
Adding Files to Zip File System of Java | Source

3.1 Prepare Source Of ZIP Copy - Windows File System

The two text files that we created are in the Windows File System. The path of these files in the Windows File Systems is retrieved by making call to the Factory method “Paths.get()”. Now, we have source location of these files in the Path references called Source1 and Source2 (Marked as 1).

Each for these file will have particular location in side the Zip file

3.2 Prepare Destination Of ZIP Copy - Zip File System

Note that we already created the Zip File (instance of FileSystem) and stored that in the reference called ZipFileSystem. Using that reference, we are getting path for the text files inside the Zip File by calling the "getPath() method". Now, we have both source and destination locations (Marked as 2). Source location is path of the Text File in the Windows File System and destination is also path but in Zip File System.

3.3 Copy Files from Windows File System to ZIP File System

Once, source and destination are defined, we making call to the "Files.Copy()" method to add content to the zip file. The “StandardCopyOption.REPLACE_EXISTING” constant option passed to the copy method will replace the already existing file (Marked as 3). The ZipFileSystem is closed at the end (Marked as 4).

4. Complete Code Example

Below is the complete code example:

//Sample 01: Package inclusion
import java.io.IOException;
        import java.net.URISyntaxException;
        import java.nio.file.*;
        import java.util.HashMap;
        import java.util.Map;
        import java.net.URI;

public class Main {
    public static void main(String[] args){
        try
        {
            //1.0 Create properties for Zip file creation
            Map<String, String> zipSysProps = new HashMap<>();
            zipSysProps.put("create", "true");

            //2.0 Form the URI for the Zip File
            Path zip_path = Paths.get("TestZipFile.zip");
            URI zip_uri = new URI("jar:file",
                    zip_path.toUri().getPath(),
                    null);

            //3.0 Create the Zip file specified by the URI
            FileSystem ZipFileSystem =
                    FileSystems.newFileSystem(
                            zip_uri,
                            zipSysProps);
            System.out.println("Zip File Created: " +
                    ZipFileSystem.toString() );

            //4.0 Get the Path of Source and 
            // Destination file and Add to Zip
            //4.1 Create the Source locations
            Path Source1 = Paths.get("SampleDoc-01.txt");
            Path Source2 = Paths.get("SampleDoc-02.txt");

            //4.2 Create Destination location in Zip
            Path Dest1 = ZipFileSystem.getPath(
                    "/SampleDoc-01.txt");
            Path Dest2 = ZipFileSystem.getPath(
                    "/SampleDoc-02.txt");

            //4.3 Copy the Source to Destination
            // (Place File one by one)
            Files.copy(
                    Source1,
                    Dest1,
                    StandardCopyOption.REPLACE_EXISTING);
            System.out.println("File Added to Zip:" + Dest1 );
            Files.copy(
                    Source2,
                    Dest2,
                    StandardCopyOption.REPLACE_EXISTING);
            System.out.println("File Added to Zip:" + Dest2 );
            ZipFileSystem.close();

        }
        catch(URISyntaxException Ex)
        {
            System.out.println("URISyntaxException: "
                    + Ex.getMessage());
        }
        catch (IOException Ex)
        {
            System.out.println("IO Exception: "
                    + Ex.getMessage());
        }
    }
}

Comments

    0 of 8192 characters used
    Post Comment

    No comments yet.

    working

    This website uses cookies

    As a user in the EEA, your approval is needed on a few things. To provide a better website experience, hubpages.com uses cookies (and other similar technologies) and may collect, process, and share personal data. Please choose which areas of our service you consent to our doing so.

    For more information on managing or withdrawing consents and how we handle data, visit our Privacy Policy at: https://hubpages.com/privacy-policy#gdpr

    Show Details
    Necessary
    HubPages Device IDThis is used to identify particular browsers or devices when the access the service, and is used for security reasons.
    LoginThis is necessary to sign in to the HubPages Service.
    Google RecaptchaThis is used to prevent bots and spam. (Privacy Policy)
    AkismetThis is used to detect comment spam. (Privacy Policy)
    HubPages Google AnalyticsThis is used to provide data on traffic to our website, all personally identifyable data is anonymized. (Privacy Policy)
    HubPages Traffic PixelThis is used to collect data on traffic to articles and other pages on our site. Unless you are signed in to a HubPages account, all personally identifiable information is anonymized.
    Amazon Web ServicesThis is a cloud services platform that we used to host our service. (Privacy Policy)
    CloudflareThis is a cloud CDN service that we use to efficiently deliver files required for our service to operate such as javascript, cascading style sheets, images, and videos. (Privacy Policy)
    Google Hosted LibrariesJavascript software libraries such as jQuery are loaded at endpoints on the googleapis.com or gstatic.com domains, for performance and efficiency reasons. (Privacy Policy)
    Features
    Google Custom SearchThis is feature allows you to search the site. (Privacy Policy)
    Google MapsSome articles have Google Maps embedded in them. (Privacy Policy)
    Google ChartsThis is used to display charts and graphs on articles and the author center. (Privacy Policy)
    Google AdSense Host APIThis service allows you to sign up for or associate a Google AdSense account with HubPages, so that you can earn money from ads on your articles. No data is shared unless you engage with this feature. (Privacy Policy)
    Google YouTubeSome articles have YouTube videos embedded in them. (Privacy Policy)
    VimeoSome articles have Vimeo videos embedded in them. (Privacy Policy)
    PaypalThis is used for a registered author who enrolls in the HubPages Earnings program and requests to be paid via PayPal. No data is shared with Paypal unless you engage with this feature. (Privacy Policy)
    Facebook LoginYou can use this to streamline signing up for, or signing in to your Hubpages account. No data is shared with Facebook unless you engage with this feature. (Privacy Policy)
    MavenThis supports the Maven widget and search functionality. (Privacy Policy)
    Marketing
    Google AdSenseThis is an ad network. (Privacy Policy)
    Google DoubleClickGoogle provides ad serving technology and runs an ad network. (Privacy Policy)
    Index ExchangeThis is an ad network. (Privacy Policy)
    SovrnThis is an ad network. (Privacy Policy)
    Facebook AdsThis is an ad network. (Privacy Policy)
    Amazon Unified Ad MarketplaceThis is an ad network. (Privacy Policy)
    AppNexusThis is an ad network. (Privacy Policy)
    OpenxThis is an ad network. (Privacy Policy)
    Rubicon ProjectThis is an ad network. (Privacy Policy)
    TripleLiftThis is an ad network. (Privacy Policy)
    Say MediaWe partner with Say Media to deliver ad campaigns on our sites. (Privacy Policy)
    Remarketing PixelsWe may use remarketing pixels from advertising networks such as Google AdWords, Bing Ads, and Facebook in order to advertise the HubPages Service to people that have visited our sites.
    Conversion Tracking PixelsWe may use conversion tracking pixels from advertising networks such as Google AdWords, Bing Ads, and Facebook in order to identify when an advertisement has successfully resulted in the desired action, such as signing up for the HubPages Service or publishing an article on the HubPages Service.
    Statistics
    Author Google AnalyticsThis is used to provide traffic data and reports to the authors of articles on the HubPages Service. (Privacy Policy)
    ComscoreComScore is a media measurement and analytics company providing marketing data and analytics to enterprises, media and advertising agencies, and publishers. Non-consent will result in ComScore only processing obfuscated personal data. (Privacy Policy)
    Amazon Tracking PixelSome articles display amazon products as part of the Amazon Affiliate program, this pixel provides traffic statistics for those products (Privacy Policy)