0

Lets say I need to have this instance new BufferedReader(new InputStreamReader(new FileInputStream(path))), what is the best way to write this using try with resource.

1. What I am used to write - because only the first Closable need to be closed

try (FileInputStream fileInputStream = new FileInputStream(path)) {
    BufferedReader reader = new BufferedReader(new InputStreamReader(fileInputStream));
    ...
}

2. The outer most Closable closes its inner Closable etc.

try (BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(path)))) {
    ...
}

3. Use a separate resource for each Closable

try (
        FileInputStream fileInputSream = new FileInputStream(path);
        InputStreamReader inputStreamReader = new InputStreamReader(fileInputSream);
        BufferedReader reader = new BufferedReader(fileInputSream)) {
    ...
}

Thanks,

Ido Sorozon

Mark Rotteveel
  • 100,966
  • 191
  • 140
  • 197
Ido Sorozon
  • 272
  • 1
  • 12
  • Your type of question appears to have been asked [many times previously on this site](https://www.google.com/search?q=java+try+with+resources+multiple+resources+site:stackoverflow.com) – Hovercraft Full Of Eels Nov 01 '18 at 14:02
  • It is a different question, I've searched the web and the only answer I could find was when I have 2 separate resources. however one of your search results [this](https://stackoverflow.com/questions/12552863/correct-idiom-for-managing-multiple-chained-resources-in-try-with-resources-bloc) touch my dilemma, maybe my search string was not good enough – Ido Sorozon Nov 01 '18 at 14:05

1 Answers1

0

I suggest a more readable option (extract method):

try (BufferedReader reader = getBufferReader()) {
Ori Marko
  • 56,308
  • 23
  • 131
  • 233