2

I'm writing a chat application in Java for didactical purposes. Of course, I met a lot of problems as I'm not an experienced programmer.

Basically my question is: Do I have to close EVERY resource (BufferedReader/Writer etc.) after the use? Even if I know I will probably reuse it?

For example: the client that waits for the user to input text, can reuse the same BufferedWriter or has to create it every time the user inputs something and then close it again?

pinusc
  • 21
  • 2
  • 3
    You can't use it after you close it. Therefore, if you're going to reuse it, don't close it every time you use it. – user253751 Nov 05 '14 at 21:25
  • 1
    Only close your resources when you know you won't be using them again – Vince Nov 05 '14 at 21:26
  • I'd say "probably" isn't a good enough reason to hang on to resources. If you *know* you'll be using it the choice is obvious. You surely don't want to close it just to open it right away or in the very near future. – ChiefTwoPencils Nov 05 '14 at 21:30
  • See also: http://stackoverflow.com/questions/18002896/is-closing-the-resources-always-important, http://stackoverflow.com/questions/24129088/are-resources-closed-before-or-after-the-finally – Grzegorz Gajos Nov 05 '14 at 21:36

1 Answers1

1

If you want to check one and the same resource multiple times, just cloes it, when you do not use it anymore. You can use try-with-resources for this purpose:

try (BufferedReader br = new BufferedReader(new FileReader(path))) {
    return br.readLine();
}
catch (IOException e) {...}
Turing85
  • 18,217
  • 7
  • 33
  • 58