Explain the close () method in Java in terms of Layman

I went through a java tutorial that allowed me to create a text file and write the words “20 Bruce Wayne” in it. The last method that is called in the main class is called closeFile (), which "closes" the text file after it is created.

Why should the file be “closed” if I really didn’t open it? By "open" I mean that the Notepad editor (not the IDE that I use) appears with the words "20 Bruce Wayne". Please answer my question in the conditions of a layman.

Main.java:

class apple {
    public static void main(String[] args)
    {
        createfile g = new createfile();
        g.openFile();
        g.addRecords();
        g.closeFile();
    }
}

createfile.java

public class createfile {
    private Formatter x;

    public void openFile(){
        try{
            x = new Formatter("supermanvsbatman.txt");
        }
        catch(Exception e){
            System.out.println("you have an error");
        }
    }
    public void addRecords(){
        x.format("%s%s%s","20 ", "Bruce ", "Wayne ");
    }
    public void closeFile(){
        x.close();
    }
}
+4
source share
3 answers

"", , , . x.close() , , .

+9

Sold Out Activist, -, , . close(), , . , ( ), , .

this.

+5

, , / close() , (java.io.IOEXCEPTION), , , public void close(), , , , , NullPointerException,   finally , - , finally

+1

All Articles