diff --git a/src/main/java/core/basesyntax/FileWork.java b/src/main/java/core/basesyntax/FileWork.java index ba2d8396..07f83ff8 100644 --- a/src/main/java/core/basesyntax/FileWork.java +++ b/src/main/java/core/basesyntax/FileWork.java @@ -1,8 +1,45 @@ package core.basesyntax; +import java.io.BufferedReader; +import java.io.FileReader; +import java.io.IOException; +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; + public class FileWork { + public String[] readFromFile(String fileName) { - //write your code here - return null; + List filteredWords = new ArrayList<>(); + try { + BufferedReader reader = new BufferedReader(new FileReader(fileName)); + String line; + while (true) { + try { + if ((line = reader.readLine()) == null) { + break; + } + } catch (IOException e) { + throw new RuntimeException(e); + } + String[] words = line.split("\\W+"); + for (String word : words) { + word = word.replaceAll("[^a-zA-Z]", "").toLowerCase(); + if (word.startsWith("w")) { + filteredWords.add(word); + } + } + } + reader.close(); + } catch (IOException e) { + throw new RuntimeException(e); + } + + Collections.sort(filteredWords); + + String[] result = new String[filteredWords.size()]; + return filteredWords.toArray(result); } + } + diff --git a/src/main/java/core/basesyntax/Main.java b/src/main/java/core/basesyntax/Main.java new file mode 100644 index 00000000..848bd91e --- /dev/null +++ b/src/main/java/core/basesyntax/Main.java @@ -0,0 +1,17 @@ +package core.basesyntax; + +import java.io.File; + +public class Main { + public static void main(String[] args) { + File file = new File("test.txt"); + + FileWork wordFilter = new FileWork(); + String fileName = file.getPath(); + String[] filteredWords = wordFilter.readFromFile(fileName); + + for (String word : filteredWords) { + System.out.println(word); + } + } +} diff --git a/test1 b/test1 index e69de29b..00c6c886 100644 --- a/test1 +++ b/test1 @@ -0,0 +1,2 @@ + +"WWW? Four-bedroom farmhouse in the countryside. Wave! All of the four double bedrooms are en suite." \ No newline at end of file