3

I'm creating a small library to read over each line of a text file and format it in a certain way, making each line available using Java 8 streams. This is similar to Files.lines(...) in the standard jdk.

I wanted to make the API as simple to use as possible, so ideally the stream would close itself after usage. ie. The user would not have to explicitly use a try-with-resources around the stream, unlike for example Files.lines (Why is Files.lines (and similar Streams) not automatically closed?).

To do so I can force the stream to call its own .close method just before running any of its terminal operations.

My question is: Is this a good idea? If not why? If yes, is this a reasonable approach?

Chers

shmosel
  • 49,289
  • 6
  • 73
  • 138
Arthur Ceccotti
  • 380
  • 2
  • 6
  • 4
    I would be strongly inclined to do nothing more than what the JDK does. Stick to the JDK's precedent. – Louis Wasserman Jul 05 '17 at 22:32
  • can you change the return type of `lines` method? because you have said: "similar to `Files.lines(...)`". – holi-java Jul 05 '17 at 23:04
  • When I say "force to call it's own .close" I mean I would probably return my own class which extends Stream and on the underlying implementation would simply call the equivalent methods in Files.lines, except for the terminal ones, where .close would be called before the actual terminal. – Arthur Ceccotti Jul 05 '17 at 23:09
  • I'm sorry, I'm not good at english. if you don't mind change your method signature. you have many choice. but it doesn't support short-circuiting operations in your approach since it often doesn't hit the last line. and it can't run the stream in parallel. – holi-java Jul 05 '17 at 23:13
  • 1
    by doing this, do you gain something extra that can't be achieved otherwise? – bichito Jul 05 '17 at 23:28
  • [You can](https://stackoverflow.com/a/31179709/2711488) create a stream that closes the I/O resources after the stream has been consumed, but there is no guaranty that the caller of your method will ever consume it. The caller could abandon the stream without ever calling a terminal operation, so the responsibility still lies at the caller. And the trick has other drawbacks, as explained in that answer… – Holger Jul 06 '17 at 17:55

0 Answers0