Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
406 views
in Technique[技术] by (71.8m points)

explain the close() method in Java in Layman's terms

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 named closeFile() that "closes" the text file after it is created.

Why does the file need to be "closed" if I didn't really open it? By "open", I mean the Notepad editor(not the IDE I'm using) pops up with the words "20 Bruce Wayne". Please answer my question in layman's terms.

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();
    }
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

When a file is "opened," the OS marks the file as locked, generally so it can't be deleted by other processes while it's being used. x.close() undoes the lock, allowing the OS and other processes to do what it wishes with the file.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...