Unable to delete a file after reading it
I'm serving a file from the file system dynamically with a jsp
开发者_如何学CHere's my code:
<%@ page import="java.io.*,java.util.*"
InputStream in = null;
OutputStream responseOut = null;
File file = new File(request.getAttribute("fileToServe"));
try{
in = new FileInputStream(file);
responseOut = response.getOutputStream();
// Transfer bytes from in to out
byte[] buf = new byte[1024];
int len;
while ((len = in.read(buf)) > 0) {
responseOut.write(buf, 0, len);
}
}finally{
if( responseOut != null ) try {
responseOut.close();
} catch( IOException ioe ){}
if( in != null ) try {
in.close();
} catch( IOException ioe ){}
}
file.delete();
%>
The problem I'm facing is, the file is delete only the first time the code is run, which is after the server restart. Subsequent calls doesn't delete the file.
I used ProcessExplorer to track this and and yeap, the Java VM is holding that file, I don't really know why is this happening.
We will run on Windows OS, always, is there a work around for this?
I've found a number of resources on the internet about this, but I can't figure out from them how to solve this problem.
What creates the file? I only see reading then deleting it in that code.
Things to watch out for:
- Reading a file requires read permissions from the file but deleting the file requires write permission from the directory; and
- Make sure you
close()
any files you create. If you don't you might lose data or it may take time to flush an implicit close.
Lastly, using an attribute like fileToServe
that comes from the user is really dangerous. I'm hoping you're sanitizing that elsewhere. You should ensure that only allowed files are served this way.
Ok, I've checked, after cletus comment, the place where this file is being created. The close
method on the stream that wrote the file was missing.
Mystery solved
cletus, please add your answer so I can accept it
精彩评论