From c90b1b2c9eda97adac00a17fab4881d909b57520 Mon Sep 17 00:00:00 2001 From: Maxim Golyak Date: Sat, 14 Dec 2024 11:43:41 +0200 Subject: [PATCH] added BufferedReader added letterForSorting --- src/main/java/core/basesyntax/FileWork.java | 50 ++++++++++++++++++++- 1 file changed, 48 insertions(+), 2 deletions(-) diff --git a/src/main/java/core/basesyntax/FileWork.java b/src/main/java/core/basesyntax/FileWork.java index ba2d8396..fab7de84 100644 --- a/src/main/java/core/basesyntax/FileWork.java +++ b/src/main/java/core/basesyntax/FileWork.java @@ -1,8 +1,54 @@ package core.basesyntax; +import java.io.BufferedReader; +import java.io.StringReader; +import java.util.Arrays; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + public class FileWork { + private static final String letterForSorting = "w"; + public String[] readFromFile(String fileName) { - //write your code here - return null; + + try { + BufferedReader bufferedReader = new BufferedReader(new StringReader(fileName)); + StringBuilder stringBuilder = new StringBuilder(); + String content = bufferedReader.readLine(); + + while (content != null) { + stringBuilder.append(content); + content = bufferedReader.readLine(); + } + String inputText = stringBuilder.toString().toLowerCase(); + + Pattern pattern = Pattern.compile("[^a-z]+"); + Matcher matcher = pattern.matcher(inputText); + String result = matcher.replaceAll(" "); + + String[] wordsArray = result.split(" "); + int count = 0; + + for (String word : wordsArray) { + if (word.startsWith(letterForSorting)) { + count++; + } + } + + String[] filteredWords = new String[count]; + int index = 0; + + for (String word : wordsArray) { + if (word.startsWith("w")) { + filteredWords[index++] = word; + } + } + Arrays.sort(filteredWords); + System.out.println(Arrays.toString(filteredWords)); + return new String[]{Arrays.toString(filteredWords)}; + } catch (Exception e) { + return new String[0]; + } } + }