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

后端 未结 6 737
旧巷少年郎
旧巷少年郎 2020-12-21 17:57

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

6条回答
  •  轮回少年
    2020-12-21 18:25

    File doesn't always need to represent an actual file, it can be something you plan on creating, are guessing at the existence of, or something you've deleted as well.

    From the JavaDoc for java.io.File:

    An abstract representation of file and directory pathnames.

    and

    Instances of this class may or may not denote an actual file-system object such as a file or a directory.

    In order to have the file actually be created, one needs to call createNEwFile(), whic according to the JavaDoc:

    Atomically creates a new, empty file named by this abstract pathname if and only if a file with this name does not yet exist.

提交回复
热议问题