Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
254 views
in Technique[技术] by (71.8m points)

java - why new FileWriter("abc.txt") creates a new file and new File("abc.txt") does not?

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.

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

Invocation of open() creates file on disk.

EDIT:

Here is how open() is defined:

/**
 * 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;

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...