If a file is opened in the class constructor, is it necessary to close it?

  • Yes, you need to close. Do you think a little gnome will come and close him for you? - Sublihim
  • 2
    Opening a file in a constructor is a very bad practice. You will not be able to construct an object without opening the file, and I generally keep quiet about exceptions in the constructor - etki
  • @Etki tell me what you need to pass in this situation: the designer needs .xml and .dtd files, first it checks the validity of .xml using the Validator , and then it reads the data if everything is OK with SAXParser . If you pass two File objects, they are not passed to the validate() method, since it requires Source , and if you pass Source , it does not accept parse() ... :( - gwgw
  • I’ll go orthogonally: why do you have a constructor doing all those things for which it is not intended? - etki
  • @Etki Well, the idea is this: the class can only be created using the .xml file, so it has 1 constructor - gwgw

1 answer 1

If a file means a stream, and if you do not use try-with-resources , then yes, you need to close it (and it doesn’t matter where you open the stream: in a method, in a constructor, or anywhere else).