I want to read a file using Flux. Basically what I am trying to do is to convert text file inside my spring-boot jar to Flux<String>
@SneakyThrows
@Override
public Flux<String> getLines() {
final InputStream inputStream = new ClassPathResource(pathToFile).getInputStream();
final InputStreamReader inputStreamReader = new InputStreamReader(inputStream);
final BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
return Flux.using(
bufferedReader::lines,
Flux::fromStream,
stringStream -> {
close(inputStreamReader);
close(bufferedReader);
stringStream.close();
}
);
}
private void close(final Closeable closeable) {
try {
closeable.close();
} catch (final IOException e) {
throw new RuntimeException(e);
}
}
I am not sure if I am doing this right, and how to improve that (however it works properly)
EDIT: I refactored it to:
return Flux.using(
() -> new ClassPathResource(pathToFile).getInputStream(),
is -> Flux.using(
() -> new InputStreamReader(is),
isr -> Flux.using(
() -> new BufferedReader(isr),
br -> Flux.using(
br::lines,
Flux::fromStream,
BaseStream::close
),
this::close
),
this::close
),
this::close
)