generated from mate-academy/jv-homework-template
-
Notifications
You must be signed in to change notification settings - Fork 1.3k
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Implement word filtering from file: return words starting with 'w' so…
…rted alphabetically.
- Loading branch information
Showing
1 changed file
with
30 additions
and
2 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; | ||
} | ||
} |