Why is it necessary to close the file?

4

Why is this line required in Java?

fout.close();

Context:

LinkedList values = new LinkedList(classe.getTurma().values());

    if (!values.isEmpty()) {

        FileOutputStream fout = null;
        String FILE = "TURMA";
        try {
            fout = new FileOutputStream(FILE);
            System.out.println("Tamanhno tuma" + values.size());
            ObjectOutputStream oos = new ObjectOutputStream(fout);
            oos.writeObject(values);

        } catch (FileNotFoundException ex) {
            Logger.getLogger(Sistema.class
                    .getName()).log(Level.SEVERE, null, ex);

        } catch (IOException ex) {
            Logger.getLogger(Sistema.class
                    .getName()).log(Level.SEVERE, null, ex);
        } finally {
            try {
                fout.close();

            } catch (IOException ex) {
                Logger.getLogger(Sistema.class
                        .getName()).log(Level.SEVERE, null, ex);
            }
        }
    }
}
    
asked by anonymous 30.11.2017 / 17:59

2 answers

11

It can be for several reasons:

  • One of these is to make the recording work. It has several file manipulation modes that only play on the disc if you need to even close it. So without closing it is not recorded.
  • If you let the operating system shut down when the process that holds you shut down you may not only not record everything you need, but you can record what you should not.
  • It may be because the file needs to be used by another process and needs to be closed for this to be possible. Unless the file was shared.
  • The open file takes up features of the operating system, such as handlers, memory, and needs some mechanism to handle it. Memory consumption is in part "charged" to your application, which can create complications if you use too much.

From the example of the question posted later, I think that only the second item does not apply, it is even rarer. Just note that the 3 catch s do the same thing and it's redundant to do so.

    
30.11.2017 / 18:13
3

close() in any programming language and operating system is basically used for:

  • If the operating system has limited resources, for example the number of open files on embedded system processors, you are wasting system resources if you do not close files with close() .

  • If the file has any kind of buffer behind it and you do not make a close() you can lose data.

  • 30.11.2017 / 18:15