Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

implemented readFromFile(...) according to README.MD requirements #1344

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
39 changes: 37 additions & 2 deletions src/main/java/core/basesyntax/FileWork.java
Original file line number Diff line number Diff line change
@@ -1,8 +1,43 @@
package core.basesyntax;

import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.Arrays;

public class FileWork {
public static final String SPECIFIED_CHARACTER = "w";
public static final String WORDS_DELIMITER = "-";
public static final String REGEX_WORD_DIVIDER = "\\W+";
public static final String[] EMPTY_ARRAY = new String[0];

public String[] readFromFile(String fileName) {
//write your code here
return null;
StringBuilder stringBuilder = new StringBuilder();
try (BufferedReader bufferedReader = new BufferedReader(new FileReader(fileName))) {
String line = bufferedReader.readLine();
while (line != null) {
stringBuilder.append(line).append(System.lineSeparator());
line = bufferedReader.readLine();
}
} catch (FileNotFoundException e) {
throw new RuntimeException("File not found.", e);
} catch (IOException e) {
throw new RuntimeException("Data can't be read", e);
}
String[] wordsSplit = String.valueOf(stringBuilder).toLowerCase().split(REGEX_WORD_DIVIDER);
StringBuilder wordsStartWithSpecifiedCharacter = new StringBuilder();
for (String word : wordsSplit) {
if (word.startsWith(SPECIFIED_CHARACTER)) {
wordsStartWithSpecifiedCharacter.append(word).append(WORDS_DELIMITER);
}
}
if (wordsStartWithSpecifiedCharacter.isEmpty() || String.valueOf(
wordsStartWithSpecifiedCharacter).isBlank()) {
return EMPTY_ARRAY;
}
String[] result = String.valueOf(wordsStartWithSpecifiedCharacter).split(WORDS_DELIMITER);
Arrays.sort(result);
return result;
}
}
Loading