diff --git a/3-0-java-core/src/main/java/com/bobocode/file_reader/FileReaderException.java b/3-0-java-core/src/main/java/com/bobocode/file_reader/FileReaderException.java new file mode 100644 index 000000000..42c440465 --- /dev/null +++ b/3-0-java-core/src/main/java/com/bobocode/file_reader/FileReaderException.java @@ -0,0 +1,7 @@ +package com.bobocode.file_reader; + +public class FileReaderException extends RuntimeException { + public FileReaderException(String message, Exception e) { + super(message, e); + } +} diff --git a/3-0-java-core/src/main/java/com/bobocode/file_reader/FileReaders.java b/3-0-java-core/src/main/java/com/bobocode/file_reader/FileReaders.java index 685d2d473..060113fd7 100644 --- a/3-0-java-core/src/main/java/com/bobocode/file_reader/FileReaders.java +++ b/3-0-java-core/src/main/java/com/bobocode/file_reader/FileReaders.java @@ -1,6 +1,15 @@ package com.bobocode.file_reader; -import com.bobocode.util.ExerciseNotCompletedException; +import java.io.IOException; +import java.net.URISyntaxException; +import java.net.URL; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.Paths; +import java.util.Objects; +import java.util.stream.Stream; + +import static java.util.stream.Collectors.joining; /** * {@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 { * @return string that holds whole file content */ public static String readWholeFile(String fileName) { - throw new ExerciseNotCompletedException(); //todo + Path filePath = createPathFromFileName(fileName); + try (Stream fileLinesStream = openFileLinesStream(filePath)) { + return fileLinesStream.collect(joining("\n")); + } + } + + private static Path createPathFromFileName(String fileName) { + Objects.requireNonNull(fileName); + URL fileUrl = FileReaders.class.getClassLoader().getResource(fileName); + try { + return Paths.get(fileUrl.toURI()); + } catch (URISyntaxException e) { + throw new FileReaderException("Invalid file URL", e); + } + } + + private static Stream openFileLinesStream(Path filePath) { + try { + return Files.lines(filePath); + } catch (IOException e) { + throw new FileReaderException("Cannot create stream of file lines!", e); + } } }