Skip to content

Gp 28 migrate file reader into exercise/completed #17

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
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);
}
}
}