Created
November 26, 2025 05:37
-
-
Save untainsYD/f5ca235323fd16625c87b35cd681f32d to your computer and use it in GitHub Desktop.
Java advanced: Laboratory 3, Task2
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| package ua.inf.iwanoff.java.advanced.lab3; | |
| import java.io.File; | |
| import java.io.IOException; | |
| import java.nio.file.*; | |
| import java.nio.file.attribute.BasicFileAttributes; | |
| import java.util.Scanner; | |
| /** | |
| * Завдання 1.2: Список файлів усіх підкаталогів. | |
| * Демонструє два підходи до обходу дерева каталогів: java.io та java.nio. | |
| */ | |
| public class Task2 { | |
| public static void main(String[] args) { | |
| Scanner scanner = new Scanner(System.in); | |
| System.out.println("=== Лабораторна робота 3. Завдання 1.2 ==="); | |
| System.out.print("Введіть шлях до теки (наприклад, src): "); | |
| String dirPath = scanner.nextLine().trim(); | |
| File dir = new File(dirPath); | |
| if (!dir.exists() || !dir.isDirectory()) { | |
| System.err.println("Помилка: Тека не існує або це не тека: " + dirPath); | |
| return; | |
| } | |
| System.out.println("\n--- Підхід 1: java.io.File (Рекурсія) ---"); | |
| listFilesRecursive(dir); | |
| System.out.println("\n--- Підхід 2: java.nio.file (FileVisitor) ---"); | |
| listFilesInNIO(Paths.get(dirPath)); | |
| scanner.close(); | |
| } | |
| /** | |
| * Підхід 1: Рекурсивний обхід за допомогою java.io.File | |
| */ | |
| public static void listFilesRecursive(File dir) { | |
| // Отримуємо список всіх файлів і папок у поточній директорії | |
| File[] files = dir.listFiles(); | |
| if (files != null) { | |
| for (File file : files) { | |
| if (file.isDirectory()) { | |
| // Якщо це папка, виводимо її назву і заходимо всередину (рекурсія) | |
| System.out.println("[DIR] " + file.getAbsolutePath()); | |
| listFilesRecursive(file); // <-- Рекурсивний виклик | |
| } else { | |
| // Якщо це файл, просто виводимо його | |
| System.out.println("[FILE] " + file.getAbsolutePath()); | |
| } | |
| } | |
| } | |
| } | |
| /** | |
| * Підхід 2: Обхід за допомогою java.nio.file.Files.walkFileTree | |
| */ | |
| public static void listFilesInNIO(Path path) { | |
| try { | |
| // walkFileTree автоматично обходить дерево і викликає методи нашого | |
| // "відвідувача" | |
| Files.walkFileTree(path, new SimpleFileVisitor<Path>() { | |
| // Викликається для кожного файлу | |
| @Override | |
| public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException { | |
| System.out.println("[FILE] " + file.toAbsolutePath()); | |
| return FileVisitResult.CONTINUE; // Продовжувати обхід | |
| } | |
| // Викликається перед тим, як зайти в папку | |
| @Override | |
| public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) throws IOException { | |
| System.out.println("[DIR] " + dir.toAbsolutePath()); | |
| return FileVisitResult.CONTINUE; | |
| } | |
| // Обробка помилок доступу до файлів | |
| @Override | |
| public FileVisitResult visitFileFailed(Path file, IOException exc) throws IOException { | |
| System.err.println("Не вдалося отримати доступ до: " + file + " (" + exc.getMessage() + ")"); | |
| return FileVisitResult.CONTINUE; | |
| } | |
| }); | |
| } catch (IOException e) { | |
| System.err.println("Помилка при обході дерева NIO: " + e.getMessage()); | |
| } | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment