Temp file is deleted after initializing an OutputStream

Viewed 29

I need to store a stream into a file and my goal is to delete the temporary file after I'm done with it. However, the temp file is deleted right after I initialize an OutputStream by specifying its absolute path. What am I missing here?

Here is my code:

    val targetFile: File = File.createTempFile(docId.toString, ".pdf")
    val path = Paths.get(targetFile.getAbsolutePath)
    val fis = new FileInputStream(targetFile)
    val outStream: OutputStream =
      Files.newOutputStream(path, StandardOpenOption.APPEND,
                            StandardOpenOption.DELETE_ON_CLOSE)
    //val outStream: OutputStream = new FileOutputStream(targetFile)
    outStream.write(buffer)
    outStream.flush()

    val doc = PDDocument.load(targetFile)
    val count = doc.getNumberOfPages

The file exists until the line

val outStream: OutputStream =
  Files.newOutputStream(path, StandardOpenOption.APPEND,
                        StandardOpenOption.DELETE_ON_CLOSE) 

but it is deleted after that line. Thank you all in advance!

0 Answers
Related