Skip to content

Commit ee2f058

Browse files
shryhustboychuk
authored andcommitted
GP-28 Add File Reader solution to exercise/completed
1 parent 787778d commit ee2f058

File tree

2 files changed

+40
-1
lines changed

2 files changed

+40
-1
lines changed
Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,7 @@
1+
package com.bobocode.file_reader;
2+
3+
public class FileReaderException extends RuntimeException {
4+
public FileReaderException(String message, Exception e) {
5+
super(message, e);
6+
}
7+
}

3-0-java-core/src/main/java/com/bobocode/file_reader/FileReaders.java

Lines changed: 33 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,17 @@
22

33
import com.bobocode.util.ExerciseNotCompletedException;
44

5+
import java.io.IOException;
6+
import java.net.URISyntaxException;
7+
import java.net.URL;
8+
import java.nio.file.Files;
9+
import java.nio.file.Path;
10+
import java.nio.file.Paths;
11+
import java.util.Objects;
12+
import java.util.stream.Stream;
13+
14+
import static java.util.stream.Collectors.joining;
15+
516
/**
617
* {@link FileReaders} provides an API that allow to read whole file into a {@link String} by file name.
718
*/
@@ -14,6 +25,27 @@ public class FileReaders {
1425
* @return string that holds whole file content
1526
*/
1627
public static String readWholeFile(String fileName) {
17-
throw new ExerciseNotCompletedException(); //todo
28+
Path filePath = createPathFromFileName(fileName);
29+
try (Stream<String> fileLinesStream = openFileLinesStream(filePath)) {
30+
return fileLinesStream.collect(joining("\n"));
31+
}
32+
}
33+
34+
private static Path createPathFromFileName(String fileName) {
35+
Objects.requireNonNull(fileName);
36+
URL fileUrl = FileReaders.class.getClassLoader().getResource(fileName);
37+
try {
38+
return Paths.get(fileUrl.toURI());
39+
} catch (URISyntaxException e) {
40+
throw new FileReaderException("Invalid file URL",e);
41+
}
42+
}
43+
44+
private static Stream<String> openFileLinesStream(Path filePath) {
45+
try {
46+
return Files.lines(filePath);
47+
} catch (IOException e) {
48+
throw new FileReaderException("Cannot create stream of file lines!", e);
49+
}
1850
}
1951
}

0 commit comments

Comments
 (0)