Showing posts with label folder. Show all posts
Showing posts with label folder. Show all posts

Thursday, January 20, 2022

How to unzip the zip file and zip the folder in Java

In this tutorial, we are going to learn how to zip the given folder and unzip the zip file using Java.

Zip the folder or directory:

Let's create a java class ZipUnzip.java and create the main method.

public static void main(String[] args) {
        String folderInputPath = "path/of/folder/to/zip";
        String outputPath = "output/path/compressed.zip";
        try {
            zip(folderInputPath, outputPath);
        } catch (IOException e) {
            System.out.println("Error due to: " + e.getMessage());
        }
    }

Now, create a method to zip the folder.

private static void zip(String folderInputPath, String outputPath) throws IOException {
        Path sourceFolderPath = Paths.get(folderInputPath);
        File zipPath = new File(outputPath);
        ZipOutputStream zos = new ZipOutputStream(new FileOutputStream(zipPath));
        Files.walkFileTree(sourceFolderPath, new SimpleFileVisitor<Path>() {
            public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
                zos.putNextEntry(new ZipEntry(sourceFolderPath.relativize(file).toString()));
                Files.copy(file, zos);
                zos.closeEntry();
                return FileVisitResult.CONTINUE;
            }
        });
        zos.close();
    }

We are using java standard core library classes to zip. Files.walkFileTree() is used to navigate recursively through the directory tree. Once we execute the code we can see the zip file is created inside the output path provided. We can verify the compression manually by extracting it.

Unzip the zip file:

Let's create a method unzip() for unzipping the compressed file

 public static void main(String[] args) {
        String zipFilePath = "zip/file/path/compressed.zip";
        String zipOutputPath = "output/path/to/unzip";
        try {
            unzip(zipFilePath, zipOutputPath);
        } catch (IOException e) {
            System.out.println("Error due to: " + e.getMessage());
        }
    }
private static void unzip(String zipFilePath, String outputDir) throws IOException {
        byte[] buffer = new byte[1024];
        ZipInputStream zis = new ZipInputStream(new FileInputStream(zipFilePath));
        ZipEntry zipEntry = zis.getNextEntry();
        while (zipEntry != null) {
            File newFile = new File(outputDir + File.separator, zipEntry.getName());
            if (zipEntry.isDirectory()) {
                if (!newFile.isDirectory() && !newFile.mkdirs()) {
                    throw new IOException("Failed to create directory " + newFile);
                }
            } else {
                File parent = newFile.getParentFile();
                if (!parent.isDirectory() && !parent.mkdirs()) {
                    throw new IOException("Failed to create directory " + parent);
                }
                FileOutputStream fos = new FileOutputStream(newFile);
                int len = 0;
                while ((len = zis.read(buffer)) > 0) {
                    fos.write(buffer, 0, len);
                }
                fos.close();
            }
            zipEntry = zis.getNextEntry();
        }
        zis.closeEntry();
        zis.close();
    }

Here, we are using ZipInputStream to read the file and FileOutputStream to write the file to the provided output directory.

The overall code implementation looks like below:

package io;

import java.io.*;
import java.nio.file.*;
import java.nio.file.attribute.BasicFileAttributes;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;
import java.util.zip.ZipOutputStream;

public class ZipUnzip {

    public static void main(String[] args) {
        String folderInputPath = "path/of/folder/to/zip";
        String outputPath = "output/path/compressed.zip";

        String zipFilePath = "zip/file/path/compressed.zip";
        String zipOutputPath = "output/path/to/unzip";
        try {
            zip(folderInputPath, outputPath);
            unzip(zipFilePath, zipOutputPath);
        } catch (IOException e) {
            System.out.println("Error due to: " + e.getMessage());
        }
    }

    private static void zip(String folderInputPath, String outputPath) throws IOException {
        Path sourceFolderPath = Paths.get(folderInputPath);
        File zipPath = new File(outputPath);
        ZipOutputStream zos = new ZipOutputStream(new FileOutputStream(zipPath));
        Files.walkFileTree(sourceFolderPath, new SimpleFileVisitor<Path>() {
            public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
                zos.putNextEntry(new ZipEntry(sourceFolderPath.relativize(file).toString()));
                Files.copy(file, zos);
                zos.closeEntry();
                return FileVisitResult.CONTINUE;
            }
        });
        zos.close();
    }

    private static void unzip(String zipFilePath, String outputDir) throws IOException {
        byte[] buffer = new byte[1024];
        ZipInputStream zis = new ZipInputStream(new FileInputStream(zipFilePath));
        ZipEntry zipEntry = zis.getNextEntry();
        while (zipEntry != null) {
            File newFile = new File(outputDir + File.separator, zipEntry.getName());
            if (zipEntry.isDirectory()) {
                if (!newFile.isDirectory() && !newFile.mkdirs()) {
                    throw new IOException("Failed to create directory " + newFile);
                }
            } else {
                File parent = newFile.getParentFile();
                if (!parent.isDirectory() && !parent.mkdirs()) {
                    throw new IOException("Failed to create directory " + parent);
                }
                FileOutputStream fos = new FileOutputStream(newFile);
                int len = 0;
                while ((len = zis.read(buffer)) > 0) {
                    fos.write(buffer, 0, len);
                }
                fos.close();
            }
            zipEntry = zis.getNextEntry();
        }
        zis.closeEntry();
        zis.close();
    }
}
Share:

Saturday, January 8, 2022

How to read only specific file from folder and sub folder using Java

In this tutorial, we are going to learn how we can learn only specific files like .png or .jpg or any other file extension which are allocated inside folder and sub-folders.

Here, what we gonna do is to list all the folders and subfolders. After that looping through the folders to filter out and get the specific desired file from those folders.

Create a sample Java class called FolderFileReader.java

Create a method that lists all the subfolders present in the folder.

 public static void listDirSubDir(String directoryName, List<String> directoryList) throws Exception {
        File directory = new File(directoryName);
        File[] fList = directory.listFiles();
        if (fList != null)
            for (File file : fList) {
                if (file.isDirectory()) {
                    String folder = file.getAbsolutePath();
                    directoryList.add(folder);
                    listDirSubDir(folder, directoryList);
                }
            }
    }

We are using recursion in order to list all the subfolders and add the available folders to the List called directoryList

Now, let's create a method that will list all the files present in the particular folder.

public static ArrayList<String> getFolderFiles(String folder) throws Exception {
        ArrayList<String> FileList = new ArrayList<String>();
        FileExtensionFilter filter = new FileExtensionFilter(extension);
        File dir = new File(folder);
        if (!dir.isDirectory()) {
            throw new Exception("Directory does not exists: " + folder);
        }
        String[] list = dir.list(filter);
        assert list != null;
        if (list.length == 0) {
            System.out.println("File not found in this folder : " + dir.getName());
        }
        for (String file : list) {
            String temp = folder + File.separator + file;
            FileList.add(temp);
        }
        return FileList;
    }

The FileExtensionFilter is the filter class used to read specific file like .png or .jpg. 

Let's create the filter class

public static class FileExtensionFilter implements FilenameFilter {

        private String ext;

        public FileExtensionFilter(String ext) {
            this.ext = ext;
        }

        public boolean accept(File dir, String name) {
            return name.endsWith(this.ext);
        }
    }

Now, implement the main method

public static void main(String[] args) {
        String directory = "folder_path";
        ArrayList<String> directoryList = new ArrayList<>();
        try {
            directoryList.add(directory); // adding current directory
            listDirSubDir(directory, directoryList);
            System.out.println("Total directory found: " + directoryList.size());
            int totalFileFound = 0;
            for (String folder : directoryList) {
                ArrayList<String> files = getFolderFiles(folder);
                for (String file : files) {
                    System.out.println(file);
                }
                totalFileFound += files.size();
            }
            System.out.println("Total files found: " + totalFileFound);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

Here, we are simply getting the list of folders available, looping through it, and getting the files present in each folder.

The overall implementation looks as below:

package io;

import java.io.File;
import java.io.FilenameFilter;
import java.util.ArrayList;
import java.util.List;

public class FolderFileReader {

    private static final String extension = ".dcm";

    public static void main(String[] args) {
        String directory = "folder_path";
        ArrayList<String> directoryList = new ArrayList<>();
        try {
            directoryList.add(directory); // adding current directory
            listDirSubDir(directory, directoryList);
            System.out.println("Total directory found: " + directoryList.size());
            int totalFileFound = 0;
            for (String folder : directoryList) {
                ArrayList<String> files = getFolderFiles(folder);
                for (String file : files) {
                    System.out.println(file);
                }
                totalFileFound += files.size();
            }
            System.out.println("Total files found: " + totalFileFound);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static void listDirSubDir(String directoryName, List<String> directoryList) throws Exception {
        File directory = new File(directoryName);
        File[] fList = directory.listFiles();
        if (fList != null)
            for (File file : fList) {
                if (file.isDirectory()) {
                    String folder = file.getAbsolutePath();
                    directoryList.add(folder);
                    listDirSubDir(folder, directoryList);
                }
            }
    }

    public static ArrayList<String> getFolderFiles(String folder) throws Exception {
        ArrayList<String> FileList = new ArrayList<String>();
        FileExtensionFilter filter = new FileExtensionFilter(extension);
        File dir = new File(folder);
        if (!dir.isDirectory()) {
            throw new Exception("Directory does not exists: " + folder);
        }
        String[] list = dir.list(filter);
        assert list != null;
        if (list.length == 0) {
            System.out.println("File not found in this folder : " + dir.getName());
        }
        for (String file : list) {
            String temp = folder + File.separator + file;
            FileList.add(temp);
        }
        return FileList;
    }

    public static class FileExtensionFilter implements FilenameFilter {

        private String ext;

        public FileExtensionFilter(String ext) {
            this.ext = ext;
        }

        public boolean accept(File dir, String name) {
            return name.endsWith(this.ext);
        }
    }
}
Share: