Search code examples
javarandomaccessfile

RandomAccessFile Dangling pointer


I am using the object RandomAccessFile to access to files with

RandomAccessFile file = new RandomAccessFile(path, "r");

My problem is if file path get removed from disk when I do perform a

file.seek(...); 

or a

file.readLine()

no exception is started, I do not have any exception.

Is it possible to have an exception in case of Dangling Pointer, if this file has been removed from disk?

Is there another method to detect the file inaccessibility ?


Solution

  • EDIT : precision for Windows (thanks to pingw33n)

    It is perfectly normal that you get no Exception when :

    • you open a file
    • you or someone else deletes the file
    • you still access to the file, read what it contained before delete, or write to it

    In fact the removal of a file do nothing to the file itself. What is removed is an entry in a directory. And the file will be actually destroyed (and the sectors it uses on disk will be released) only when :

    • no more directory entries point to it
    • no file descriptors keep it opened

    So even if the byte you ask in not buffered in memory, the file system still knows how to get it from disk. By the way, it is a common pattern to create temporary files, that is files that will be deleted on last close.

    Of course, you can do what merlin2011 suggests, that is test the presence of the file via its path. But you must know that is the file is deleted and then created again, the path (that was used to open the file) is present, but points to a totaly different object.

    So if you really need that the file actually reflects the content of the directory, you cannot keep it opened and must reopen it at each and every acces ... It this is not a fair option you still can:

    • ignore modification to directory and file system ; you have a file and you use it, full stop. There are many use cases where this is correct.
    • state in you documentation that the directory is yours and nobody else should delete a file in it. And after all you cannot prevent an admin to break its system or kill your app.

    This is true for all normal filesystems, all those of Linux or other Unix like systems, NTFS, etc. I am not sure that it is still true for older one such such as CPM or FAT, but they are no longer currently used in production :-). But under Windows, it should not be possible to delete a file currently opened in a java application.

    To answer precisely to you 2 questions :

    • your pointer is not dangling but still points to a real file (even if nobody else can see it)
    • Exception will be thrown in case of file inaccessibility (physical damage to disk or connections, file system errors, etc.). But if only the entry was removed, the file is still accessible