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

查看:23
本文介绍了用外行的术语解释 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:

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.

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

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