Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

java

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

like image 492
Diplav Avatar asked Nov 26 '25 11:11

Diplav


2 Answers

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;
like image 180
AlexR Avatar answered Nov 28 '25 01:11

AlexR


I think file.createNewFile() creates the new file in actual.. please see following code for 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());
like image 37
Imran Avatar answered Nov 28 '25 00:11

Imran



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!