Last active
September 17, 2020 06:11
-
-
Save jvorhauer/d64f446a238eea82a5f6e63e351f58e4 to your computer and use it in GitHub Desktop.
Java 11 - Read a Resource
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// No dependencies, NIO 2.0 | |
public String read(final String resource) { | |
var in = getClass().getClassLoader().getResource(resource); | |
return new String(Files.readAllBytes(Paths.get(in.toURI()))); | |
} | |
// IOUtils + Vavr, Apache Commons | |
public String read() { | |
return Option.of(getClass().getClassLoader().getResourceAsStream(fn)) | |
.flatMap(in -> Try.of(() -> IOUtils.toString(in, StandardCharsets.UTF_8)).toOption()) | |
.getOrElse(""); | |
} | |
// As Vavr is a given anyway, prefer the second solution; switch to Either as result if error message is important | |
// or maybe, combine first and second solution: | |
public String read() { | |
return Option.of(getClass().getClassLoader().getResourceAsStream(fn)) | |
.flatMap(in -> Try.of(() -> new String(Files.readAllBytes(Paths.get(in.toURI()))).toOption()) | |
.getOrElse(""); | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Last solution not checked very much yet...