Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Do I need to close files I perform File.getName() on?

Tags:

java

file

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?

like image 216
user957183 Avatar asked Nov 21 '11 12:11

user957183


People also ask

Why do you need to close file after you are done using it?

If you write to a file without closing, the data won't make it to the target file.

Do we need to close file object in 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.

Is Close file necessary in Python?

You've learned why it's important to close files in Python. Because files are limited resources managed by the operating system, making sure files are closed after use will protect against hard-to-debug issues like running out of file handles or experiencing corrupted data.

What will happen if we dont close file in Java?

As long as your program is running, if you keep opening files without closing them, the most likely result is that you will run out of file descriptors/handles available for your process, and attempting to open more files will fail eventually.


2 Answers

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.

like image 183
nfechner Avatar answered Oct 23 '22 10:10

nfechner


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

like image 44
Sumit Singh Avatar answered Oct 23 '22 10:10

Sumit Singh