File deleted before being read, InputStream from file, DELETE_ON_CLOSE

Viewed 42

Why is my file being deleted before I read it? How is that even possible?

I am using the api java.nio.file.Files.newInputStream(<path>, StandardOpenOption.DELETE_ON_CLOSE) to create an input stream backed from a file, such that (given the 2nd parameter), the file is deleted once the stream is closed.

I would have expected the file to exist in the system until I consume the stream, but from my experiments, this happens before. I am at odds as to how this can be?

import java.nio.file.{Files, Path, Paths, StandardOpenOption}

val folder = Paths.get("/home/cmhteixeira/Desktop/fooBar/")  // parent folder 
val newFile = Files.write(Paths.get(folder.toString, "temp.txt"), "Hello world".getBytes)
val inputStream = Files.newInputStream(newFile, StandardOpenOption.DELETE_ON_CLOSE)
Thread.sleep(4000)  // useful for when I test for file existence with bash `ls -lah`
val filesInFooBarFolder = folder.toFile.listFiles().toList
println(s"Files in fooBar: ${filesInFooBarFolder.mkString(" # ")}")
Thread.sleep(4000) 
println("Content is: " + scala.io.Source.fromInputStream(inputStream).mkString)

The response is:

Files in fooBar: 
Content is: Hello world

This is unexpected and prevents me from verifying that a file was created. Additionally if I try to test for the existence of the file using ls -lah /home/cmhteixeira/Desktop/fooBar/, then I also cannot see the file.

I have tried this with java 8 and java 11. OS is linux.

Does anyone know how this behaviour is possible?

0 Answers
Related