1. import java.io.BufferedReader;
  2. import java.io.BufferedWriter;
  3. import java.io.File;
  4. import java.io.FileReader;
  5. import java.io.FileWriter;
  6. import java.io.IOException;
  7. import java.util.ArrayList;
  8. import java.util.List;
  9. public class DirectoryArchiver {
  10. public static void archiveDirectory(String sourceDir, String destinationFile) {
  11. File source = new File(sourceDir);
  12. if (!source.exists() || !source.isDirectory()) {
  13. System.err.println("Error: Source directory does not exist or is not a directory.");
  14. return;
  15. }
  16. try (BufferedWriter writer = new BufferedWriter(new FileWriter(destinationFile))) {
  17. List<String> files = listFiles(source);
  18. for (String file : files) {
  19. String filePath = source.getAbsolutePath() + "/" + file; // Construct full path
  20. try(BufferedReader reader = new BufferedReader(new FileReader(filePath))) {
  21. String line;
  22. while ((line = reader.readLine()) != null) {
  23. writer.write(line);
  24. writer.newLine();
  25. }
  26. }
  27. }
  28. } catch (IOException e) {
  29. System.err.println("Error archiving directory: " + e.getMessage());
  30. }
  31. }
  32. private static List<String> listFiles(File dir) {
  33. List<String> fileList = new ArrayList<>();
  34. File[] files = dir.listFiles();
  35. if (files != null) {
  36. for (File file : files) {
  37. if (file.isFile()) {
  38. fileList.add(file.getName());
  39. } else if (file.isDirectory()) {
  40. // Optionally recursively archive subdirectories
  41. //fileList.addAll(listFiles(file));
  42. }
  43. }
  44. }
  45. return fileList;
  46. }
  47. public static void main(String[] args) {
  48. String sourceDirectory = "source_directory"; // Replace with your source directory
  49. String destinationFile = "archive.txt"; // Replace with your desired destination file
  50. archiveDirectory(sourceDirectory, destinationFile);
  51. System.out.println("Directory archived to " + destinationFile);
  52. }
  53. }

Add your comment