Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
package com.bobocode.file_reader;

public class FileReaderException extends RuntimeException {
public FileReaderException(String message, Exception e) {
super(message, e);
}
}
Original file line number Diff line number Diff line change
@@ -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.
Expand All @@ -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<String> 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<String> openFileLinesStream(Path filePath) {
try {
return Files.lines(filePath);
} catch (IOException e) {
throw new FileReaderException("Cannot create stream of file lines!", e);
}
}
}