用Layman的术语解释Java中的close()方法 [英] explain the close() method in Java in Layman's terms

查看:84
本文介绍了用Layman的术语解释Java中的close()方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我经历了一个java教程,允许我创建一个文本文件并在其中写下20 Bruce Wayne。在主类中调用的最后一个方法名为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 called in the main class is named closeFile() that "closes" the text file after it is created.

如果我没有真正打开文件,为什么文件需要关闭?通过打开,我的意思是记事本编辑器(不是我正在使用的IDE)弹出20 Bruce Wayne字样。请以外行的方式回答我的问题。

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:

Main.java:

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

createfile.java

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();
    }
}


推荐答案

一个文件被打开,操作系统将文件标记为已锁定,通常在使用时不能被其他进程删除。 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.

这篇关于用Layman的术语解释Java中的close()方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆