17

I'll be having lot of files in a directory. I'll be just getting the file names using File.getName() and log them to a log file. I presume, I don't need to close the file since I'm not doing any read/write operation in it.

Is this correct?

user2428118
  • 7,935
  • 4
  • 45
  • 72
user957183
  • 417
  • 3
  • 10
  • 20
  • If you want to list the files in a directory, you may use [`File#list()`](http://download.oracle.com/javase/6/docs/api/java/io/File.html#list%28%29) – MByD Nov 21 '11 at 12:29
  • 1
    If you open a file then you need to close it, but the `File` class doesn't represent an open file, it just represents a path. – Wyzard Nov 21 '11 at 12:30
  • got it. thank you all for your reply, thanks. – user957183 Nov 21 '11 at 12:32
  • If the answers helped you, please rather upvote them and - what is even more important - accept the best one. – Line Jan 26 '18 at 14:34

4 Answers4

42

You never have to close Files, because it is basically a representation of a path. Only Streams and Readers/Writers. In fact, File does not even have a close() method.

nfechner
  • 17,295
  • 7
  • 45
  • 64
6
Only resources needed to be close.

In java API there is a interface Closeable Interface, those classes implement this interface they need to be close after use.

close() //method is in that interface..  

And use of close is

It closes the stream and releases any system resources associated with it. 
If the stream is already closed then invoking this method has no effect.

File is no need to be close

Sumit Singh
  • 15,743
  • 6
  • 59
  • 89
1

That is correct. Note that there is no File.close() method.

Andrew Thompson
  • 168,117
  • 40
  • 217
  • 433
0

Yes, that's correct. When you open a file by creating a FileInputStream or a FileOutputStream, you must close the stream at the end.

Christoph Walesch
  • 2,337
  • 2
  • 32
  • 44