From d88b6bd1346552b4e69ed96e414c5eba813b6a21 Mon Sep 17 00:00:00 2001 From: Oleh Ridchenko Date: Thu, 26 Sep 2024 16:28:54 +0300 Subject: [PATCH] filter out only the words starting with w --- src/main/java/core/basesyntax/FileWork.java | 42 ++++++++++++++++++++- 1 file changed, 40 insertions(+), 2 deletions(-) diff --git a/src/main/java/core/basesyntax/FileWork.java b/src/main/java/core/basesyntax/FileWork.java index ba2d8396..1abe7663 100644 --- a/src/main/java/core/basesyntax/FileWork.java +++ b/src/main/java/core/basesyntax/FileWork.java @@ -1,8 +1,46 @@ 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 { public String[] readFromFile(String fileName) { - //write your code here - return null; + StringBuilder stringBuilder = new StringBuilder(); + File myFile = new File(fileName); + + try (BufferedReader bufferedWriter = new BufferedReader(new FileReader(myFile))) { + String line; + while ((line = bufferedWriter.readLine()) != null) { + stringBuilder.append(line.toLowerCase()).append(" "); + } + } catch (IOException e) { + throw new RuntimeException("Can't run this file", e); + } + + String[] splitArray = stringBuilder.toString().split("\\W+"); + + int count = 0; + for (String word : splitArray) { + if (word.startsWith("w")) { + count++; + } + } + + if (count == 0) { + return new String[0]; + } + + String[] sortedArray = new String[count]; + int index = 0; + for (int i = 0; i < splitArray.length; i++) { + if (splitArray[i].startsWith("w")) { + sortedArray[index++] = splitArray[i]; + } + } + Arrays.sort(sortedArray); + return sortedArray; } }