1. import java.io.*;
  2. import java.util.zip.ZipInputStream;
  3. import java.util.zip.ZipOutputStream;
  4. public class FileArchiver {
  5. public static void archiveFiles(String[] filePaths, String archiveFilePath) throws IOException {
  6. // Check if filePaths array is valid
  7. if (filePaths == null || filePaths.length == 0) {
  8. System.err.println("Error: No file paths provided.");
  9. return;
  10. }
  11. // Create the archive file
  12. try (ZipOutputStream zos = new ZipOutputStream(new FileOutputStream(archiveFilePath))) {
  13. for (String filePath : filePaths) {
  14. // Check if file exists
  15. File file = new File(filePath);
  16. if (!file.exists()) {
  17. System.err.println("Warning: File not found: " + filePath);
  18. continue; // Skip to the next file
  19. }
  20. // Add the file to the archive
  21. zos.putNextEntry(new ZipEntry(file.getName()));
  22. try (FileInputStream fis = new FileInputStream(file)) {
  23. zos.write(fis.readAllBytes()); // Write the file content to the archive
  24. }
  25. }
  26. }
  27. }
  28. public static void main(String[] args) throws IOException {
  29. // Example usage
  30. String[] filesToArchive = {"file1.txt", "file2.txt", "folder/file3.txt"}; // Replace with your file paths
  31. String archiveName = "archive.zip"; // Replace with your desired archive file name
  32. // Create dummy files for testing
  33. try {
  34. new File("file1.txt").createNewFile();
  35. new File("file2.txt").createNewFile();
  36. File folder = new File("folder");
  37. folder.mkdir();
  38. new File("folder/file3.txt").createNewFile();
  39. } catch (IOException e) {
  40. System.err.println("Error creating dummy files: " + e.getMessage());
  41. return;
  42. }
  43. try {
  44. archiveFiles(filesToArchive, archiveName);
  45. System.out.println("Files archived successfully to: " + archiveName);
  46. } catch (IOException e) {
  47. System.err.println("Error archiving files: " + e.getMessage());
  48. }
  49. }
  50. }

Add your comment