gpt4 book ai didi

java - 为什么 new FileWriter ("abc.txt") 创建一个新文件而 new File ("abc.txt") 不创建?

转载 作者:行者123 更新时间:2023-12-03 20:24:23 25 4
gpt4 key购买 nike

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

最佳答案

java.io.File 类的构造函数不会在磁盘上创建文件。它只是文件路径的抽象。该文件是在您写入文件时创建的。

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

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

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

编辑:

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;

关于java - 为什么 new FileWriter ("abc.txt") 创建一个新文件而 new File ("abc.txt") 不创建?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8630484/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com