Skip to content

Commit

Permalink
Implement word filtering from file: return words starting with 'w' so…
Browse files Browse the repository at this point in the history
…rted alphabetically.
  • Loading branch information
RVoinahii committed Sep 25, 2024
1 parent 160910a commit e6c4ad0
Showing 1 changed file with 30 additions and 2 deletions.
32 changes: 30 additions & 2 deletions src/main/java/core/basesyntax/FileWork.java
Original file line number Diff line number Diff line change
@@ -1,8 +1,36 @@
package core.basesyntax;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class FileWork {
public String[] readFromFile(String fileName) {
//write your code here
return null;
File inputFile = new File(fileName);
List<String> wordsStartingWithW = new ArrayList<>();

try (BufferedReader incomingFileReader = new BufferedReader(new FileReader(inputFile));) {
String currentLine;

while ((currentLine = incomingFileReader.readLine()) != null) {
currentLine = currentLine.replaceAll("[^a-zA-Z\\s]", "").trim();
String[] words = currentLine.split("\\s+");

for (String word : words) {
if (word.toLowerCase().startsWith("w")) {
wordsStartingWithW.add(word.toLowerCase());
}
}
}
} catch (IOException e) {
throw new RuntimeException("Cant read file" + e);
}
String[] filteredResult = wordsStartingWithW.toArray(new String[0]);
Arrays.sort(filteredResult);
return filteredResult;
}
}

0 comments on commit e6c4ad0

Please sign in to comment.