S
S
SoloCheater2018-08-07 15:28:20
Java
SoloCheater, 2018-08-07 15:28:20

How to exclude files with a specific extension from being packaged in a Java ZIP archive?

Hello. In general, there is such a (below) code configured to pack files / folders into a ZIP archive.

package ru.app;

import java.io.Closeable;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URI;
import java.util.Deque;
import java.util.LinkedList;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

public class Main {
  
  public static void pack(File directory, String to) throws IOException {
    URI base = directory.toURI();
    Deque<File> queue = new LinkedList<File>();
    queue.push(directory);
    OutputStream out = new FileOutputStream(new File(to));
    Closeable res = out;

    try {
      ZipOutputStream zout = new ZipOutputStream(out);
      res = zout;
      while (!queue.isEmpty()) {
        directory = queue.pop();
        for (File child : directory.listFiles()) {
          String name = base.relativize(child.toURI()).getPath();
          if (child.isDirectory()) {
            queue.push(child);
            name = name.endsWith("/") ? name : name + "/";
            zout.putNextEntry(new ZipEntry(name));
          } else {
            zout.putNextEntry(new ZipEntry(name));
            InputStream in = new FileInputStream(child);
            try {
              byte[] buffer = new byte[1024];
              while (true) {
                int readCount = in.read(buffer);
                if (readCount < 0) {
                  break;
                }
                zout.write(buffer, 0, readCount);
              }
            } finally {
              in.close();
            }
            zout.closeEntry();
          }
        }
      }
    } finally {
      res.close();
    }
  }
  
  public static void main(String[] args) throws IOException {
    pack(new File("C:/Test"), "C:/test.zip");
  }

}

This code packs generally all the files that are only in the desired directory.
And I need to make an exception from this, that is, do not pack files, for example, with the .dat extension.
How can I do that?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
E
Evgeny T., 2018-08-07
@SoloCheater

See String.matches(). Add a condition before archiving:
if (!name.matches(".*\\.dat(:|$).*")) {
... archive
}

I
illusor, 2018-08-07
@iLLuzor

The File class has methods listFiles(FileFilter filter) and listFiles(FilenameFilter filter) . With their help, you can get a list of files by your own filter.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question