|
| 1 | +import java.io.*; |
| 2 | +import java.util.zip.ZipEntry; |
| 3 | +import java.util.zip.ZipInputStream; |
| 4 | +import java.util.zip.ZipOutputStream; |
| 5 | + |
| 6 | +public class martinbohorquez { |
| 7 | + public static void main(String[] args) throws FileNotFoundException { |
| 8 | + File sourceFile = new File("AZ900-2024.pdf"); |
| 9 | + File zipFile = zipFile(sourceFile); |
| 10 | + System.out.printf("El archivo '%s' ha sido comprimido: %s%n", sourceFile, zipFile); |
| 11 | + File unzipFile = unzipFile(zipFile); |
| 12 | + System.out.printf("El archivo '%s' ha sido descomprimido: %s%n", zipFile, unzipFile); |
| 13 | + } |
| 14 | + |
| 15 | + private static File zipFile(File sourceFile) throws FileNotFoundException { |
| 16 | + if (!sourceFile.exists()) throw new FileNotFoundException("El archivo no existe: " + sourceFile); |
| 17 | + |
| 18 | + String fileName = sourceFile.toString() |
| 19 | + .substring(0, sourceFile.toString().lastIndexOf(".")); |
| 20 | + File targetFile = new File(fileName.concat(".zip")); |
| 21 | + |
| 22 | + try (FileOutputStream fos = new FileOutputStream(targetFile); |
| 23 | + ZipOutputStream zipOut = new ZipOutputStream(fos); |
| 24 | + FileInputStream fis = new FileInputStream(sourceFile)) { |
| 25 | + |
| 26 | + ZipEntry zipEntry = new ZipEntry(sourceFile.getName()); |
| 27 | + zipOut.putNextEntry(zipEntry); |
| 28 | + |
| 29 | + byte[] buffer = new byte[1024]; |
| 30 | + int length; |
| 31 | + while ((length = fis.read(buffer)) >= 0) zipOut.write(buffer, 0, length); |
| 32 | + |
| 33 | + zipOut.closeEntry(); |
| 34 | + } catch (IOException e) { |
| 35 | + throw new RuntimeException(e); |
| 36 | + } |
| 37 | + return targetFile; |
| 38 | + } |
| 39 | + |
| 40 | + private static File unzipFile(File sourceFile) throws FileNotFoundException { |
| 41 | + if (!sourceFile.exists()) throw new FileNotFoundException("El archivo no existe: " + sourceFile); |
| 42 | + File targetFile = null; |
| 43 | + try (FileInputStream fis = new FileInputStream(sourceFile); |
| 44 | + ZipInputStream zipOut = new ZipInputStream(fis)) { |
| 45 | + |
| 46 | + ZipEntry zipEntry; |
| 47 | + |
| 48 | + if ((zipEntry = zipOut.getNextEntry()) != null) { |
| 49 | + targetFile = new File("unzip-" + zipEntry.getName()); |
| 50 | + try (FileOutputStream fos = new FileOutputStream(targetFile)) { |
| 51 | + byte[] buffer = new byte[1024]; |
| 52 | + int length; |
| 53 | + while ((length = zipOut.read(buffer)) >= 0) fos.write(buffer, 0, length); |
| 54 | + } |
| 55 | + |
| 56 | + zipOut.closeEntry(); |
| 57 | + } |
| 58 | + } catch (IOException e) { |
| 59 | + throw new RuntimeException(e); |
| 60 | + } |
| 61 | + return targetFile; |
| 62 | + } |
| 63 | +} |
0 commit comments