0

I expected any file can't be deleted while their stream is being used.

but with this code the following job is executed and it works fine.

  • open file input stream
  • delete the file
  • wait for 10 seconds
  • write a file with the input stream

Could anyone please teach me why my code works? How could the stream still have the information? will this still okay even if the file is Super large? like, twice a memory?

public static void main(String[] args) throws IOException {
    final String HOME = System.getProperty("user.home");
    final String ORIGINAL = HOME + "/Downloads/test.jpeg";
    final String TARGET = HOME + "/Downloads/targetFile.jpeg";

    File file = new File(ORIGINAL);
    try (InputStream inputStream = Files.newInputStream(file.toPath())
    ) {
        if (file.delete()) {
            log.info("Original file deleted");
        } else {
            log.info("Failed deleting the original file");
        }

        for (int i = 0; i < 10; i++) {
            log.info("waits {}/10s", i + 1);
            Thread.sleep(1000);
        }

        File targetFile = new File(TARGET);
        Files.copy(inputStream, targetFile.toPath(), StandardCopyOption.REPLACE_EXISTING);

        if (targetFile.isFile()) {
            log.info("target file created");
            if (targetFile.renameTo(file)) {
                log.info("target file renamed");
            } else {
                log.info("target file rename failed");
            }
        } else {
            log.info("{} is not a file", targetFile);
        }

    } catch (InterruptedException e) {
        throw new RuntimeException(e);
    }
}

It still works perfectly. I tested it on Linux and MacOS as well, but still both are OK. Could anyone please give me some hint to understand this situation? I got so confused.

Mark Rotteveel
  • 100,966
  • 191
  • 140
  • 197
Shane Park
  • 81
  • 4
  • 3
    This is a side effect of how files work on Unix-like OSes like Linux and MacOS. The same wouldn't work on Windows, because you wouldn't be able to rename or delete the file while it was open for reading or writing. – Mark Rotteveel Jun 08 '22 at 12:22
  • Thanks a lot Mark. Now I understand how it happened. appreciate it – Shane Park Jun 12 '22 at 13:27

0 Answers0