From 6752df85ac8ca89eebf3831ebd0eff0fb14feafc Mon Sep 17 00:00:00 2001 From: Rostyslav Novak Date: Sat, 28 Sep 2024 22:58:58 +0300 Subject: [PATCH] complited task --- src/main/java/core/basesyntax/FileWork.java | 47 ++++++++++++++++++++- 1 file changed, 46 insertions(+), 1 deletion(-) diff --git a/src/main/java/core/basesyntax/FileWork.java b/src/main/java/core/basesyntax/FileWork.java index ba2d8396..728f3daf 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 int INDEX_OF_FIRST_CHAR = 0; + private static final int STARTING_INDEX = 0; + public String[] readFromFile(String fileName) { //write your code here - return null; + File file = new File(fileName); + String[] wordsStartingWithW; + + try (BufferedReader bufferedReader = new BufferedReader(new FileReader(file))) { + StringBuilder stringBuilder = new StringBuilder(); + String value = bufferedReader.readLine(); + + while (value != null) { + stringBuilder.append(value).append(" "); + value = bufferedReader.readLine(); + } + String[] words = stringBuilder.toString().split("\\W+"); + + int counter = 0; + for (String word : words) { + if (!word.isEmpty() && (word.charAt(0) == 'w' || word.charAt(0) == 'W')) { + counter++; + } + } + wordsStartingWithW = new String[counter]; + + int index = STARTING_INDEX; + for (String word : words) { + if (!word.isEmpty() && (word.charAt(INDEX_OF_FIRST_CHAR) == 'w' + || word.charAt(0) == 'W')) { + wordsStartingWithW[index] = word.toLowerCase(); + index++; + } + } + + Arrays.sort(wordsStartingWithW); + + } catch (IOException e) { + throw new RuntimeException("Error" + e.getMessage(), e); + } + + return wordsStartingWithW; } }