2

Here is my sample code:

public static void main(String[] args) throws IOException {
  FileInputStream a = new FileInputStream("/tmp/input");
  File file = new File("/tmp/input");
  try {
    boolean isFileDeleted = file.delete();
    System.out.println("Is file deleted successfully : "+ isFileDeleted);
  } catch (Exception e) {
    e.printStackTrace();
  }
  FileOutputStream outputStream = new FileOutputStream("/tmp/output");
  IOUtils.copyLarge(a, outputStream);
}

Output:

Is file deleted successfully: true

enter image description here

And I am seeing the input file is deleted successfully also from /tmp folder and I am also seeing output file got created with the expected output. How FileInputStream read the File and copy the expected character even if the file is deleted from the disk?

Anshita Singh
  • 1,583
  • 1
  • 17
  • 40
  • I think you need to close stream for FileInputStream, because your stream saved file inside of a. Also if you don't close stream, you will take memory leak FileInputStream a = new FileInputStream("/tmp/input"); a.close(); or use try with resource. try (FileInputStream a = new FileInputStream("/tmp/input")) { // your program code } – Yeras_QazaQ Apr 24 '23 at 08:49

1 Answers1

0

Great question, and I see why the above code counters your expectations. The reason why this happens is how certain file systems handle file deletion.

Usually, file deletion does not, by default, mean 'erase the file data'. It simply means 'erase the file system entry pointing to that data'. In other words, the data is still there, it's simply 'forgotten' by the file system.

Since it is 'forgotten', eventually it will simply be overwritten with the data of another file. This is also why you can, in many cases, recover data from a faulty disk by simply fixing the file entries. For the same reason, data recovery experts strongly suggest to immediately cease to use a disk you're planning to recover data from - to avoid the accidental overwriting.

On top of all that, the low level OS procedures dealing with file access will often delay actual file deletion until all open handles have been closed, and the file handles themselves will remain valid. Here is how Linux systems behave, for instance.

crizzis
  • 9,978
  • 2
  • 28
  • 47
  • 1
    It's worth noting that this behaviour is pretty fundamental to how unix-like operating systems behave in general and many features depend on it. It's also the reason why the package-manager can just overwrite (delete/replace) a shared library that's still in use with a newer version: anything that has already got that file open/mapped will continue to see and use the old version. Anything that opens it up afterwards will see the new one. – Joachim Sauer Apr 24 '23 at 09:10