Created
November 26, 2025 05:45
-
-
Save untainsYD/a43c8005fcbb5625045c9adeb70e80fd to your computer and use it in GitHub Desktop.
Java advanced: Laboratory 3, Task3
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.IOException; | |
| import java.nio.charset.StandardCharsets; | |
| import java.nio.file.Files; | |
| import java.nio.file.Path; | |
| import java.nio.file.Paths; | |
| import java.nio.file.StandardOpenOption; | |
| import java.util.Comparator; | |
| import java.util.List; | |
| import java.util.stream.Collectors; | |
| import java.util.stream.Stream; | |
| /** | |
| * Завдання 1.3: Робота з текстовими файлами засобами Stream API. | |
| */ | |
| public class Task3 { | |
| public static void main(String[] args) { | |
| System.out.println("=== Лабораторна робота 3. Завдання 1.3 ==="); | |
| // Визначаємо шляхи до файлів (папка results) | |
| Path inputFile = Paths.get("results/lab3_task3_input.txt"); | |
| Path outputFile = Paths.get("results/lab3_task3_output.txt"); | |
| // 1. Підготовка: створюємо файл з тестовими даними | |
| createTestFile(inputFile); | |
| System.out.println("Вхідний файл: " + inputFile.toAbsolutePath()); | |
| System.out.println("Вихідний файл: " + outputFile.toAbsolutePath()); | |
| // 2. Основна логіка (Stream API) | |
| try (Stream<String> lines = Files.lines(inputFile, StandardCharsets.UTF_8)) { | |
| List<String> processedLines = lines | |
| // Фільтрація: рядки, що містять літеру "a" (латинську) | |
| .filter(line -> line.contains("a")) | |
| // Сортування: за збільшенням довжини | |
| .sorted(Comparator.comparingInt(String::length)) | |
| .collect(Collectors.toList()); | |
| // 3. Запис результату | |
| Files.write(outputFile, processedLines, StandardCharsets.UTF_8, | |
| StandardOpenOption.CREATE, StandardOpenOption.TRUNCATE_EXISTING); | |
| System.out.println("\n>>> Обробка завершена успішно!"); | |
| System.out.println("Кількість рядків у результаті: " + processedLines.size()); | |
| // Виведення вмісту для перевірки | |
| System.out.println("\nВміст вихідного файлу:"); | |
| processedLines.forEach(System.out::println); | |
| } catch (IOException e) { | |
| System.err.println("Помилка при роботі з файлами: " + e.getMessage()); | |
| e.printStackTrace(); | |
| } | |
| } | |
| /** | |
| * Створює тестовий файл із набором слів. | |
| */ | |
| private static void createTestFile(Path path) { | |
| try { | |
| if (!Files.exists(path.getParent())) { | |
| Files.createDirectories(path.getParent()); | |
| } | |
| List<String> content = List.of( | |
| "Elephant", // містить 'a' | |
| "Cat", // містить 'a' | |
| "Dog", // НЕ містить 'a' | |
| "Apple", // не містить 'a' (тільки велика 'A'), якщо регістр важливий. У завданні "літеру | |
| // 'a'", зазвичай це точний збіг. | |
| "Banana", // містить 'a' | |
| "Java", // містить 'a' | |
| "Stream API", // містить 'a' | |
| "Code" // НЕ містить 'a' | |
| ); | |
| Files.write(path, content, StandardCharsets.UTF_8, | |
| StandardOpenOption.CREATE, StandardOpenOption.TRUNCATE_EXISTING); | |
| System.out.println("Створено тестовий файл: " + path.getFileName()); | |
| } catch (IOException e) { | |
| System.err.println("Не вдалося створити тестовий файл: " + e.getMessage()); | |
| } | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment