为什么新的FileWriter("abc.txt")创建一个新文件而新的File("abc.txt")却没有? [英] why new FileWriter("abc.txt") creates a new file and new File("abc.txt") does not?

查看:45
本文介绍了为什么新的FileWriter("abc.txt")创建一个新文件而新的File("abc.txt")却没有?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

新File("abc.txt")不会创建实际文件.在查看源代码时,我发现 new FileWriter("abc.txt")最终创建了一个文件对象,如 new File()

new File("abc.txt") does not create actual file while new FileWriter("abc.txt") creates a file on disk. While going through source code i found that new FileWriter("abc.txt") eventually creates an object of file like new File()

推荐答案

java.io.File 的构造方法未在磁盘上创建文件.它只是文件路径的抽象.当您写入文件时,将创建该文件.

Constructor of Class java.io.File does not create file on disk. It is just a abstraction over the file path. The file is created when you write to the file.

在创建 FileWriter 时,它将调用 FileOutputStream 的构造函数,该构造函数调用一系列安全检查,然后调用:

When you are creating FileWriter it calls constructor of FileOutputStream that calls a sequence of security checks and then invokes:

if (append) {
    openAppend(name);
} else {
    open(name);
}

调用 open()会在磁盘上创建文件.

Invocation of open() creates file on disk.

以下是 open()的定义方式:

/**
 * Opens a file, with the specified name, for writing.
 * @param name name of file to be opened
 */
private native void open(String name) throws FileNotFoundException;

这篇关于为什么新的FileWriter("abc.txt")创建一个新文件而新的File("abc.txt")却没有?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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