11package 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