开发者

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

开发者 https://www.devze.com 2023-03-29 00:10 出处:网络
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 calle开发者_开发知识库d in the main class is named closeFile(

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 calle开发者_开发知识库d 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();
    }
}


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.


In addition to the answer of Sold Out Activist, when you are working with i/o operations, such as files, you are using a stream to add text to your file, or extract text from your file. This stream must be closed, with the method close(), when you are exiting your program, because you could lose data. It's like a saving operation, if you don't save your file (close the stream), you will lose the changes made on file.

See this example, and this.


is used for closing the file which is opened in write mode because to reduce/to make secure our data we use close() method and it throws exception like (java.io.IOEXCEPTION) why means any method call with respect to object only because it is public void close() that means it is instance so it is calls with respect with object so in some times is there a chance to getting object to get null any method calls with respect to null reference then it getting NullPointerException so this is the code code in finally block means what ever files we open that and all relinquished in finally block


The close() method of Reader Class in Java is used to close the stream and release the resources that were busy in the stream, if any. This method has following results: If the stream is open, it closes the stream releasing the resources. If the stream is already closed, it will have no effect.

0

精彩评论

暂无评论...
验证码 换一张
取 消