#2602 Temp file Being locked by creation

jhughes Wed 19 Apr

I have some local resources in a pod I need to move to temporary files for access outside of the pod. The first method takes a file and copies it into a temporary file and returns the uri.

private Uri tempFileUri(File f)
{
  tempFile := File.createTemp(f.name,DateTime.now.toJava().toStr)
  tempFile.deleteOnExit()

  try
  {
    //Read source file into buffer
    buf := f.readAllBuf
    //Write the buffer into the temp file
    tempFile.out.writeBuf(buf)
  }
  finally
  {
    tempFile.out.close();
    tempFile.in.close();
  }
  return (tempFile.uri);
}

The next step is attempting to execute the file (it is an executable) using the Process class.

buf := Buf()
Process() 
{
  command = Str[execFile.toFile.osPath]
  out = buf.out 
}.run.join

but somewhere in this process fantom is locking that temporary file.

Cannot run program <filePath>: CreateProcess error=32, The process cannot access the file because it is being used by another process

filePath above is replacing the true file path.

jhughes Wed 19 Apr

Additionally on temp file issues, deleteOnExit appears to have no effect as every time i've run this program for testing, the temp files persist and are not deleted.

SlimerDude Wed 19 Apr

Every time you call File.out() you create a new OutStream, so you don't ever close the original output stream that you write too. (I'm not sure why you're opening and closing an InStream in the finally clause either.)

A cleaner solution would be:

private Uri tempFileUri(File f) {
    tempFile := File.createTemp(f.name, DateTime.now.toJava().toStr)

    buf := f.readAllBuf
    out := tempFile.out

    try     out.writeBuf(buf)
    finally out.close()

    return tempFile.uri
}

Additionally, the temp file probably isn't being deleted because, as pointed out, it's locked! Also, only a clean JVM exit will invoke the file deletion code and Java's File.deleteOnExit() method has long known to be evil!, so you're probably best not using it anyway.

jhughes Wed 19 Apr

I was attempting to close everything trying to get the file released, didn't know a new output stream was being created every time File.out was used. Closing the correct stream was the solution.

Thanks.

go4 Thu 20 Apr

The try-catch is not convenience.

I propose api File.writeAllBuf, File.writeAllStr.

SlimerDude Thu 20 Apr

Good idea!

Given there's already a File.readAllBuf() so a complementary File.writeAllBuf() would be nice!

Login or Signup to reply.