import java.io.*;
import java.util.zip.ZipInputStream;
import java.util.zip.ZipOutputStream;
public class FileArchiver {
public static void archiveFiles(String[] filePaths, String archiveFilePath) throws IOException {
// Check if filePaths array is valid
if (filePaths == null || filePaths.length == 0) {
System.err.println("Error: No file paths provided.");
return;
}
// Create the archive file
try (ZipOutputStream zos = new ZipOutputStream(new FileOutputStream(archiveFilePath))) {
for (String filePath : filePaths) {
// Check if file exists
File file = new File(filePath);
if (!file.exists()) {
System.err.println("Warning: File not found: " + filePath);
continue; // Skip to the next file
}
// Add the file to the archive
zos.putNextEntry(new ZipEntry(file.getName()));
try (FileInputStream fis = new FileInputStream(file)) {
zos.write(fis.readAllBytes()); // Write the file content to the archive
}
}
}
}
public static void main(String[] args) throws IOException {
// Example usage
String[] filesToArchive = {"file1.txt", "file2.txt", "folder/file3.txt"}; // Replace with your file paths
String archiveName = "archive.zip"; // Replace with your desired archive file name
// Create dummy files for testing
try {
new File("file1.txt").createNewFile();
new File("file2.txt").createNewFile();
File folder = new File("folder");
folder.mkdir();
new File("folder/file3.txt").createNewFile();
} catch (IOException e) {
System.err.println("Error creating dummy files: " + e.getMessage());
return;
}
try {
archiveFiles(filesToArchive, archiveName);
System.out.println("Files archived successfully to: " + archiveName);
} catch (IOException e) {
System.err.println("Error archiving files: " + e.getMessage());
}
}
}
Add your comment