Java writing to a deleted file
Asked Answered
C

3

12

I'm using FileWriter to write to a file and noticed that even after I have deleted the file (out of process) the FileWriter does not throw any exception.

Is this normal?

Carouse answered 6/2, 2012 at 18:7 Comment(1)
What OS is this on? For example, in Linux doing rm only disassociates the file from its path, and only when all handles to the file are gone will it actually be deleted (it can actually be recovered easily if it is still open).Magalymagan
R
16

This depends on your operating system:

  • On Windows, you'd typically not be able to delete an open file.
  • On Unix, deleting an open file and continuing to write into it (or read from it) is perfectly acceptable. Once you delete the file, it will no longer have a directory entry. However, its contents will continue to exist on disk until the file is closed. Once all open handles that refer to the file get closed, the OS will automatically reclaim the disk space.
Roane answered 6/2, 2012 at 18:9 Comment(0)
M
1

Yes, it's normal. Using most of the conventional ways of doing I/O, if the file doesn't exist, it creates it for you. This of course pending that you deleted it before you began writing to it.

Midinette answered 6/2, 2012 at 18:10 Comment(0)
M
0

A file can appear in more than one place (with hard links) Deleting a file removes one of the hard links (possibly the only) If there is a link somewhere else, the file is still accessible.

Files which are deleted, but open continue to take up disk space and if large enough can mean your space used and the size of all the files you can find on your disk is different.

BTW: You can read/write the contents of an open file (deleted or not) if you look in /proc/{pid}/fd/{fid}

Macneil answered 6/2, 2012 at 19:19 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.