From 21e2a641372aef78d45779e27a3ad5e5f8bcb1bc Mon Sep 17 00:00:00 2001 From: Mykola Date: Sat, 4 Jan 2025 22:35:24 +0200 Subject: [PATCH] make task --- src/main/java/core/basesyntax/FileWork.java | 25 +++++++++++++++++++-- 1 file changed, 23 insertions(+), 2 deletions(-) diff --git a/src/main/java/core/basesyntax/FileWork.java b/src/main/java/core/basesyntax/FileWork.java index ba2d8396..9c9d387b 100644 --- a/src/main/java/core/basesyntax/FileWork.java +++ b/src/main/java/core/basesyntax/FileWork.java @@ -1,8 +1,29 @@ package core.basesyntax; +import java.io.*; +import java.util.ArrayList; + public class FileWork { public String[] readFromFile(String fileName) { - //write your code here - return null; + ArrayList resultList = new ArrayList<>(); + File file = new File(fileName); + + try (BufferedReader bufferedReader = new BufferedReader(new FileReader(file))) { + String line; + while ((line = bufferedReader.readLine()) != null) { + String[] words = line.split("\\W+"); + for (String word : words) { + if (!word.isEmpty() && word.toLowerCase().startsWith("w")) { + resultList.add(word.toLowerCase()); + } + } + } + } catch (FileNotFoundException e) { + throw new RuntimeException("Can't open the file", e); + } catch (IOException e) { + throw new RuntimeException("Error while reading the file", e); + } + + return resultList.stream().sorted().toArray(String[]::new); } }