From 3ac9b99d74ed66f1db8cb85be193efec4ee90682 Mon Sep 17 00:00:00 2001 From: Serhii Holenkov Date: Sat, 28 Dec 2024 13:46:02 +0200 Subject: [PATCH] Realised method readFromFile which receive fileName as a link to the file and method create array filtered by SPECIFIED_CHARACTER --- src/main/java/core/basesyntax/FileWork.java | 49 ++++++++++++++++++++- 1 file changed, 47 insertions(+), 2 deletions(-) diff --git a/src/main/java/core/basesyntax/FileWork.java b/src/main/java/core/basesyntax/FileWork.java index ba2d8396..4854da14 100644 --- a/src/main/java/core/basesyntax/FileWork.java +++ b/src/main/java/core/basesyntax/FileWork.java @@ -1,8 +1,53 @@ package core.basesyntax; +import java.io.BufferedReader; +import java.io.File; +import java.io.FileReader; +import java.io.IOException; +import java.util.Arrays; + public class FileWork { + private static final char SPECIFIED_CHARACTER = 'w'; + public String[] readFromFile(String fileName) { - //write your code here - return null; + File file = new File(fileName); + if (file.length() == 0) { + return new String[0]; + } + StringBuilder stringBuilder = new StringBuilder(); + try (BufferedReader bufferedReader = new BufferedReader(new FileReader(file))) { + String line = bufferedReader.readLine(); + while (line != null) { + stringBuilder.append(line).append(System.lineSeparator()); + line = bufferedReader.readLine(); + } + } catch (IOException e) { + throw new RuntimeException("Unable to read the file", e); + } + String[] stringArray = stringBuilder.toString().toLowerCase() + .split("\\s+"); + for (int i = 0; i < stringArray.length; i++) { + stringArray[i] = stringArray[i].replaceAll("[^a-z]", ""); + } + int specifiedCharWordsCounter = 0; + for (String stringStartedAtW : stringArray) { + if(stringStartedAtW.charAt(0) == SPECIFIED_CHARACTER) { + specifiedCharWordsCounter++; + } + } + if (specifiedCharWordsCounter == 0) { + return new String[0]; + } + String[] filteredArray = new String[specifiedCharWordsCounter]; + int j = 0; + for (String word : stringArray) { + if (!word.isEmpty() && word.charAt(0) == SPECIFIED_CHARACTER) { + filteredArray[j] = word; // Добавляем слово в массив + j++; // Увеличиваем индекс для следующего элемента + } + } + Arrays.sort(filteredArray); + + return filteredArray; } }