Skip to content

Commit c874d38

Browse files
authored
Merge pull request #17 from bobocode-projects/GP-28_Migrate_File_Reader_into_exercise/completed
Gp 28 migrate file reader into exercise/completed
2 parents 97be0be + b917396 commit c874d38

File tree

2 files changed

+39
-2
lines changed

2 files changed

+39
-2
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: 32 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,15 @@
11
package com.bobocode.file_reader;
22

3-
import com.bobocode.util.ExerciseNotCompletedException;
3+
import java.io.IOException;
4+
import java.net.URISyntaxException;
5+
import java.net.URL;
6+
import java.nio.file.Files;
7+
import java.nio.file.Path;
8+
import java.nio.file.Paths;
9+
import java.util.Objects;
10+
import java.util.stream.Stream;
11+
12+
import static java.util.stream.Collectors.joining;
413

514
/**
615
* {@link FileReaders} provides an API that allow to read whole file into a {@link String} by file name.
@@ -14,6 +23,27 @@ public class FileReaders {
1423
* @return string that holds whole file content
1524
*/
1625
public static String readWholeFile(String fileName) {
17-
throw new ExerciseNotCompletedException(); //todo
26+
Path filePath = createPathFromFileName(fileName);
27+
try (Stream<String> fileLinesStream = openFileLinesStream(filePath)) {
28+
return fileLinesStream.collect(joining("\n"));
29+
}
30+
}
31+
32+
private static Path createPathFromFileName(String fileName) {
33+
Objects.requireNonNull(fileName);
34+
URL fileUrl = FileReaders.class.getClassLoader().getResource(fileName);
35+
try {
36+
return Paths.get(fileUrl.toURI());
37+
} catch (URISyntaxException e) {
38+
throw new FileReaderException("Invalid file URL", e);
39+
}
40+
}
41+
42+
private static Stream<String> openFileLinesStream(Path filePath) {
43+
try {
44+
return Files.lines(filePath);
45+
} catch (IOException e) {
46+
throw new FileReaderException("Cannot create stream of file lines!", e);
47+
}
1848
}
1949
}

0 commit comments

Comments
 (0)