new FileWriter("abc.txt")
在磁盘上创建文件时,new File("abc.txt")
不会创建实际的文件。在浏览源代码时,我发现new FileWriter("abc.txt")
最终创建了一个类似于new File()
的文件对象
发布于 2011-12-26 00:47:28
类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;
发布于 2013-10-25 21:52:37
我认为file.createNewFile()在实际中创建了新文件。请参阅下面的detal代码。
File file = new File("D:\\tables\\test.sql");
// if file does not exists, then create it
if (!file.exists()) {
file.createNewFile();
}
FileWriter fw = new FileWriter(file.getAbsoluteFile());
发布于 2011-12-26 00:48:46
File
并不总是需要表示实际的文件,它可以是您计划创建的文件,可以是猜测存在的文件,也可以是您已经删除的文件。
从java.io.File的JavaDoc
是文件和目录路径名的抽象表示形式。
和
此类的
实例可能表示也可能不表示实际的文件系统对象,如文件或目录。
为了实际创建文件,需要调用createNEwFile()
,根据JavaDoc:
当且仅当具有此抽象路径名的文件尚不存在时,
才以原子方式创建一个以此抽象路径名命名的新空文件。
https://stackoverflow.com/questions/8630484
复制相似问题