Answer the question
In order to leave comments, you need to log in
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");
}
}
Answer the question
In order to leave comments, you need to log in
See String.matches(). Add a condition before archiving:
if (!name.matches(".*\\.dat(:|$).*")) {
... archive
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question