Suggest a feature
×

Welcome to TagMyCode

Please login or create account to add a snippet.
0
0
 
0
Language: Java
Posted by: user969a8
Added: Jun 10, 2020 2:21 PM
Modified: Jun 10, 2020 2:25 PM
Views: 144
Tags: no tags
  1. import static java.util.stream.Collectors.joining;
  2.  
  3. /**
  4.  * {@link FileReader} provides an API that allow to read whole file into a {@link String} by file name.
  5.  */
  6. public class FileReader {
  7.  
  8.     /**
  9.      * Returns a {@link String} that contains whole text from the file specified by name.
  10.      *
  11.      * @param fileName a name of a text file
  12.      * @return string that holds whole file content
  13.      */
  14.     public static String readWholeFileFromResources(String fileName) {
  15.         Path filePath = createPathFromFileName(fileName);
  16.         try (Stream<String> fileLinesStream = openFileLinesStream(filePath)) {
  17.             return fileLinesStream.collect(joining("\n"));
  18.         }
  19.     }
  20.  
  21.     private static Stream<String> openFileLinesStream(Path filePath) {
  22.         try {
  23.             return Files.lines(filePath);
  24.         } catch (IOException e) {
  25.             throw new FileReaderException("Cannot create stream of file lines!", e);
  26.         }
  27.     }
  28.  
  29.     private static Path createPathFromFileName(String fileName) {
  30.         Objects.requireNonNull(fileName);
  31.         URL fileUrl = FileReader.class.getClassLoader().getResource(fileName);
  32.         try {
  33.             return Paths.get(fileUrl.toURI());
  34.         } catch (URISyntaxException e) {
  35.             throw new FileReaderException("Invalid file URL",e);
  36.         }
  37.     }
  38. }
Comments disabled