2
2
3
3
import com .bobocode .util .ExerciseNotCompletedException ;
4
4
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
+
5
16
/**
6
17
* {@link FileReaders} provides an API that allow to read whole file into a {@link String} by file name.
7
18
*/
@@ -14,6 +25,27 @@ public class FileReaders {
14
25
* @return string that holds whole file content
15
26
*/
16
27
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
+ }
18
50
}
19
51
}
0 commit comments