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?
-
3If you look into Java API, you will be able to get the answer immediately.gigadot– gigadot2011-01-20 20:37:32 +00:00Commented Jan 20, 2011 at 20:37
-
55I've learned that people are more helpful than the otherwise superb Java spec.Albus Dumbledore– Albus Dumbledore2011-01-20 20:40:40 +00:00Commented Jan 20, 2011 at 20:40
-
7b/c it cannot be opened :)bestsss– bestsss2011-01-20 20:45:43 +00:00Commented Jan 20, 2011 at 20:45
-
6Because it doesn't open anything. And people are considerably less reliable than the offical Java specification.user207421– user2074212014-12-18 10:08:43 +00:00Commented Dec 18, 2014 at 10:08
6 Answers
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.)
Comments
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.
3 Comments
Path completely.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.
1 Comment
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();