Skip to content

Instantly share code, notes, and snippets.

@jvorhauer
Last active September 17, 2020 06:11
Show Gist options
  • Save jvorhauer/d64f446a238eea82a5f6e63e351f58e4 to your computer and use it in GitHub Desktop.
Save jvorhauer/d64f446a238eea82a5f6e63e351f58e4 to your computer and use it in GitHub Desktop.
Java 11 - Read a Resource
// 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("");
}
@jvorhauer
Copy link
Author

Last solution not checked very much yet...

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment