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

JavaFile Io

Java Problem Overview


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

Java Solutions


Solution 1 - Java

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

Solution 2 - Java

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.

Solution 3 - Java

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.

Solution 4 - Java

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

Solution 5 - Java

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.

Solution 6 - Java

As already stated, the File class does not have a closing method as it's merely a path or a reference to the actual File.

You will usually use this File class as a helper to open the actual file with a FileReader class which you can close. That said, it does close itself on exit but if you read a file from your program and then try to do something to this file externally, it could result in an error on that external call, so it's better to close it

File path = new File(/some/path/file.txt);
FileReader actualFile = new FileReader(path);
...<
if(imDoneWithTheFile)
    actualFile.close();

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionAlbus DumbledoreView Question on Stackoverflow
Solution 1 - JavabiziclopView Answer on Stackoverflow
Solution 2 - JavaaxtavtView Answer on Stackoverflow
Solution 3 - JavaSpeckView Answer on Stackoverflow
Solution 4 - JavaSaher AhwalView Answer on Stackoverflow
Solution 5 - JavaBalaji Boggaram RamanarayanView Answer on Stackoverflow
Solution 6 - JavapierView Answer on Stackoverflow