Delete file after viewing connection using FileInputStream

I have a temporary file that I want to send to the client from the controller in the Play Framework. Can I delete a file after opening a connection using FileInputStream? For example, can I do something like this -

File file = getFile(); InputStream is = new FileInputStream(file); file.delete(); renderBinary(is, "name.txt"); 

What if the file is a large file? If I delete the file, will subsequent reads () on the InputStream give an error? I tried files about 1 MB in size. I am not getting an error message.

Sorry if this is a very naive question, but I could not find anything related to it, and I'm pretty new to Java

+6
source share
2 answers

I just came across this exact same scenario in some code that I was asked to work on. The programmer created a temporary file, receiving the input stream on it, deleting the temporary file, and then calling renderBinary. It seems to work just fine even for very large files, even in gigabytes.

I was surprised by this and still looking for additional documentation that shows why this works.

UPDATE: Finally, we came across a file that made this thing bomb. I think it was over 3 GB. At this point, it became necessary NOT to delete the file during rendering processing. I actually ended up using the Amazon Queue service to queue messages for these files. Messages are then retrieved on a job with a scheduled deletion. Works well, even with clustered servers on a load balancer.

+1
source

It seems contradictory that FileInputStream can still read after deleting the file.

DiskLruCache , a popular library in the Android world, originating from the libcore Android platform, even relies on this “feature” as shown below:

 // Open all streams eagerly to guarantee that we see a single published // snapshot. If we opened streams lazily then the streams could come // from different edits. InputStream[] ins = new InputStream[valueCount]; try { for (int i = 0; i < valueCount; i++) { ins[i] = new FileInputStream(entry.getCleanFile(i)); } } catch (FileNotFoundException e) { .... 

As @EJP pointed out in his commentary on a similar question: "How Unix and Linux work. Deleting a file really removes its name from the directory: inode and data are saved until all processes open."

But I don’t think it’s a good idea to rely on him.

0
source

Source: https://habr.com/ru/post/954131/


All Articles