Skip to content

Instantly share code, notes, and snippets.

@mrocabado
Created October 16, 2020 20:00
Show Gist options
  • Save mrocabado/3f72af1a6ca476b072ab5b3fa7bfed89 to your computer and use it in GitHub Desktop.
Save mrocabado/3f72af1a6ca476b072ab5b3fa7bfed89 to your computer and use it in GitHub Desktop.
Zip/Unzip en Java
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.mindwaresrl</groupId>
<artifactId>zip-files</artifactId>
<version>1.0-SNAPSHOT</version>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.6.1</version>
<configuration>
<source>1.8</source>
<target>1.8</target>
</configuration>
</plugin>
</plugins>
</build>
</project>
package com.mindwaresrl.unzipfiles;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Optional;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;
public class UnzipMain {
private static final String EMPTY_STRING = "";
private static final int BUFFER_SIZE = 4096;
public static void main(String[] args) {
if (args.length < 1) {
throw new IllegalStateException("File argument required");
}
Path pathToZip = Paths.get(args[0]);
if (!isValidZip(pathToZip)) {
throw new IllegalStateException("Missing or Invalid ZIP file");
}
unzipFile(pathToZip);
}
private static boolean isValidZip(Path pathToZip) {
return pathToZip.toFile().exists() && pathToZip.toFile().isFile() && "zip".equalsIgnoreCase( getFileExtension(pathToZip.getFileName().toString()) );
}
private static void unzipFile(Path pathToZip) {
try ( ZipInputStream zipStream = new ZipInputStream(new FileInputStream(pathToZip.toFile())) ) {
Path targetFolderPath = pathToZip.getParent().resolve(removeFileExtension(pathToZip.getFileName().toString()));
cleanFolder(targetFolderPath);
ZipEntry zipEntry = zipStream.getNextEntry();
while (zipEntry != null) {
if (zipEntry.getName().endsWith(".pdf")) {
zipEntry = zipStream.getNextEntry();
continue;
}
Path targetFile = targetFolderPath.resolve(zipEntry.getName());
saveZipEntry(zipStream, targetFile);
zipEntry = zipStream.getNextEntry();
}
} catch (IOException e) {
e.printStackTrace();
}
}
private static void saveZipEntry(ZipInputStream zipStream, Path targetFile) throws IOException {
byte[] buffer = new byte[BUFFER_SIZE];
try (FileOutputStream fos = new FileOutputStream(targetFile.toFile())) {
int len;
while ((len = zipStream.read(buffer)) > 0) {
fos.write(buffer, 0, len);
}
}
}
private static void cleanFolder(Path targetFolderPath) throws IOException {
File targetFolder = targetFolderPath.toFile();
if (targetFolder.exists()) {
Files.walk(targetFolder.toPath())
.map(Path::toFile)
.forEach(File::delete);
}
if (!targetFolder.exists()) {
targetFolder.mkdirs();
}
}
//You could also use FilenameUtils.getExtension from Apache Commons IO Library
private static String getFileExtension(String filename) {
return Optional.ofNullable(filename)
.filter(name -> name.contains("."))
.map(name -> name.substring(filename.lastIndexOf(".") + 1))
.orElse("");
}
private static String removeFileExtension(String filename) {
if ( EMPTY_STRING.equals(getFileExtension(filename)) ) {
return filename;
}
return filename.substring(0, filename.lastIndexOf("."));
}
}
package com.mindwaresrl.zipfiles;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Objects;
import java.util.stream.Stream;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
public class ZipMain {
public static void main(String[] args) {
if (args.length < 1) {
throw new IllegalStateException("Folder argument required");
}
Path pathToFolder = Paths.get(args[0]);
if (!isValidFolder(pathToFolder)) {
throw new IllegalStateException("Missing or Invalid folder");
}
zipFolder(pathToFolder);
}
private static boolean isValidFolder(Path pathToZip) {
return pathToZip.toFile().exists() && pathToZip.toFile().isDirectory() && Objects.nonNull(pathToZip.getParent());
}
private static void zipFolder(Path contentFolder) {
String zipFileName = contentFolder.getFileName() + ".zip";
File zipFile = contentFolder.getParent().resolve(zipFileName).toFile();
if (zipFile.exists()) {
throw new IllegalStateException(zipFile.toPath().toString() + " already exists");
}
try (FileOutputStream zipFos = new FileOutputStream(zipFile); ZipOutputStream zipOut = new ZipOutputStream(zipFos) ) {
try (Stream<Path> filesToZip = Files.list(contentFolder))
{
filesToZip.map(Path::toFile)
.filter(fileToZip -> fileToZip.getName().endsWith("txt"))
.forEach(fileToZip -> zipFile(fileToZip, zipOut));
}
} catch (IOException e) {
e.printStackTrace();
}
}
private static void zipFile(File fileToZip, ZipOutputStream zipOut) {
try (FileInputStream fileToZipFis = new FileInputStream(fileToZip)) {
ZipEntry zipEntry = new ZipEntry(fileToZip.getName());
zipOut.putNextEntry(zipEntry);
byte[] bytes = new byte[4096];
int length;
while((length = fileToZipFis.read(bytes)) >= 0) {
zipOut.write(bytes, 0, length);
}
} catch(IOException e) {
throw new RuntimeException(e);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment