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.
Realised method readFromFile which receive fileName as a link to the …
…file and method create array filtered by SPECIFIED_CHARACTER
- Loading branch information
Showing
1 changed file
with
47 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,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 char SPECIFIED_CHARACTER = 'w'; | ||
|
||
public String[] readFromFile(String fileName) { | ||
//write your code here | ||
return null; | ||
File file = new File(fileName); | ||
if (file.length() == 0) { | ||
return new String[0]; | ||
} | ||
StringBuilder stringBuilder = new StringBuilder(); | ||
try (BufferedReader bufferedReader = new BufferedReader(new FileReader(file))) { | ||
String line = bufferedReader.readLine(); | ||
while (line != null) { | ||
stringBuilder.append(line).append(System.lineSeparator()); | ||
line = bufferedReader.readLine(); | ||
} | ||
} catch (IOException e) { | ||
throw new RuntimeException("Unable to read the file", e); | ||
} | ||
String[] stringArray = stringBuilder.toString().toLowerCase() | ||
.split("\\s+"); | ||
for (int i = 0; i < stringArray.length; i++) { | ||
stringArray[i] = stringArray[i].replaceAll("[^a-z]", ""); | ||
} | ||
int specifiedCharWordsCounter = 0; | ||
for (String stringStartedAtW : stringArray) { | ||
if(stringStartedAtW.charAt(0) == SPECIFIED_CHARACTER) { | ||
specifiedCharWordsCounter++; | ||
} | ||
} | ||
if (specifiedCharWordsCounter == 0) { | ||
return new String[0]; | ||
} | ||
String[] filteredArray = new String[specifiedCharWordsCounter]; | ||
int j = 0; | ||
for (String word : stringArray) { | ||
if (!word.isEmpty() && word.charAt(0) == SPECIFIED_CHARACTER) { | ||
filteredArray[j] = word; // Добавляем слово в массив | ||
j++; // Увеличиваем индекс для следующего элемента | ||
} | ||
} | ||
Arrays.sort(filteredArray); | ||
|
||
return filteredArray; | ||
} | ||
} |