Why doesn't java.io.File have a close method?

后端 未结 5 1993
不知归路
不知归路 2020-11-29 23:53

While java.io.RandomAccessFile does have a close() method java.io.File doesn\'t. Why is that? Is the file closed automatically on fina

相关标签:
5条回答
  • 2020-11-29 23:57

    The javadoc of the File class describes the class as:

    An abstract representation of file and directory pathnames.

    File is only a representation of a pathname, with a few methods concerning the filesystem (like exists()) and directory handling but actual streaming input and output is done elsewhere. Streams can be opened and closed, files cannot.

    (My personal opinion is that it's rather unfortunate that Sun then went on to create RandomAccessFile, causing much confusion with its inconsistent naming.)

    0 讨论(0)
  • 2020-11-29 23:57

    A BufferedReader can be opened and closed but a File is never opened, it just represents a path in the filesystem.

    0 讨论(0)
  • 2020-11-30 00:06

    Say suppose, you have

    File f  = new File("SomeFile");
    f.length();
    

    You need not close the Files, because its just the representation of a path.

    You should always consider to close only reader/writers and in fact streams.

    0 讨论(0)
  • 2020-11-30 00:07

    Essentially random access file wraps input and output streams in order to manage the random access. You don't open and close a file, you open and close streams to a file.

    0 讨论(0)
  • 2020-11-30 00:13

    java.io.File doesn't represent an open file, it represents a path in the filesystem. Therefore having close method on it doesn't make sense.

    Actually, this class was misnamed by the library authors, it should be called something like Path.

    0 讨论(0)
提交回复
热议问题