|
| 1 | +package com.bobocode.util; |
| 2 | + |
| 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; |
| 13 | + |
| 14 | +/** |
| 15 | + * {@link FileReader} provides an API that allow to read whole file into a {@link String} by file name. |
| 16 | + */ |
| 17 | +public class FileReader { |
| 18 | + |
| 19 | + /** |
| 20 | + * Returns a {@link String} that contains whole text from the file specified by name. |
| 21 | + * |
| 22 | + * @param fileName a name of a text file |
| 23 | + * @return string that holds whole file content |
| 24 | + */ |
| 25 | + public static String readWholeFileFromResources(String fileName) { |
| 26 | + Path filePath = createPathFromFileName(fileName); |
| 27 | + try (Stream<String> fileLinesStream = openFileLinesStream(filePath)) { |
| 28 | + return fileLinesStream.collect(joining("\n")); |
| 29 | + } |
| 30 | + } |
| 31 | + |
| 32 | + private static Stream<String> openFileLinesStream(Path filePath) { |
| 33 | + try { |
| 34 | + return Files.lines(filePath); |
| 35 | + } catch (IOException e) { |
| 36 | + throw new FileReaderException("Cannot create stream of file lines!", e); |
| 37 | + } |
| 38 | + } |
| 39 | + |
| 40 | + private static Path createPathFromFileName(String fileName) { |
| 41 | + Objects.requireNonNull(fileName); |
| 42 | + URL fileUrl = FileReader.class.getClassLoader().getResource(fileName); |
| 43 | + try { |
| 44 | + return Paths.get(fileUrl.toURI()); |
| 45 | + } catch (URISyntaxException e) { |
| 46 | + throw new FileReaderException("Invalid file URL",e); |
| 47 | + } |
| 48 | + } |
| 49 | +} |
0 commit comments