|
| 1 | +import java.io.*; |
| 2 | +import java.util.zip.ZipEntry; |
| 3 | +import java.util.zip.ZipOutputStream; |
| 4 | + |
| 5 | +public class MohamedElderkaoui { |
| 6 | + |
| 7 | + public static void main(String[] args) { |
| 8 | + String filePath = "archivo.txt"; // Cambia esta ruta por la del archivo a comprimir |
| 9 | + String zipFilePath = "archivo.zip"; // Ruta donde se guardará el archivo comprimido |
| 10 | + |
| 11 | + try { |
| 12 | + compressToZip(filePath, zipFilePath); |
| 13 | + System.out.println("Archivo comprimido correctamente en: " + zipFilePath); |
| 14 | + } catch (IOException e) { |
| 15 | + System.err.println("Error al comprimir el archivo: " + e.getMessage()); |
| 16 | + } |
| 17 | + } |
| 18 | + |
| 19 | + // Método para comprimir un archivo en formato ZIP |
| 20 | + public static void compressToZip(String filePath, String zipFilePath) throws IOException { |
| 21 | + File fileToZip = new File(filePath); |
| 22 | + if (!fileToZip.exists()) { |
| 23 | + throw new FileNotFoundException("El archivo no existe: " + filePath); |
| 24 | + } |
| 25 | + |
| 26 | + // Crear flujo de salida para el archivo ZIP |
| 27 | + try (FileOutputStream fos = new FileOutputStream(zipFilePath); |
| 28 | + ZipOutputStream zipOut = new ZipOutputStream(fos); |
| 29 | + FileInputStream fis = new FileInputStream(fileToZip)) { |
| 30 | + |
| 31 | + // Crear una entrada de ZIP para el archivo |
| 32 | + ZipEntry zipEntry = new ZipEntry(fileToZip.getName()); |
| 33 | + zipOut.putNextEntry(zipEntry); |
| 34 | + |
| 35 | + // Leer y escribir los datos del archivo en el archivo ZIP |
| 36 | + byte[] buffer = new byte[1024]; |
| 37 | + int length; |
| 38 | + while ((length = fis.read(buffer)) >= 0) { |
| 39 | + zipOut.write(buffer, 0, length); |
| 40 | + } |
| 41 | + |
| 42 | + // Cerrar la entrada ZIP |
| 43 | + zipOut.closeEntry(); |
| 44 | + } |
| 45 | + } |
| 46 | +} |
0 commit comments