Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java File release resource

Tags:

java

file

spring

I am using SpringFramework Web MVC and inside the servlet handleRequestInternal, I created a variable to access a file in the local filesystem, i.e.

protected ModelAndView handleRequestInternal(HttpServletRequest request,......
{
......
 File file = new File(rssPath);
 if( !file.exists() ) {
  file.createNewFile();
  FileWriter outFile = new FileWriter(rssPath);
  outFile.write(rssJson);
  outFile.flush();
  //file = null;
 }
}

The question is, if I don't set the file to null, the file will still be in use and I can't write to it.

I have to wait a few seconds, probably until GC comes to collect.

Looking at the File API, I don't see any method such as close() to release the resources.

So how do I destroy the file reference properly (without setting it to null, am I missing something ?) ?

like image 301
Lydon Ch Avatar asked Apr 30 '26 06:04

Lydon Ch


1 Answers

You can't close Files. But you HAVE to close FileInputStream, FIleOutputStream, FileReader and FileWriter. Otherwise these Streams (and File-Handles) will not be GCed. (until the Object holding the Stream is GCed)

EDIT: Do this in a finally-Block, to be sure close is called.

like image 157
Christian Kuetbach Avatar answered May 02 '26 19:05

Christian Kuetbach



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!