0

I have an Array[Byte], which was initially in pdf format. I need to convert it to java.io.File. Update: I have an email-service, which can send emails with attachments (files). Files must be in java.io.File format. But files in the request to my service come as Array[Byte] with base64 encoding. I can't afford file creation every time, because it will clog my memory.

3
  • Do you want to write it to a file system? Commented May 6, 2020 at 9:09
  • @IvanStanislavciuc no, I need to take it to val without creating a new file Commented May 6, 2020 at 9:18
  • I don't think this is possible. Please tell us what you actually want to solve. Bring more context to the question. Commented May 6, 2020 at 9:20

1 Answer 1

2

java.io.File is not a storage of the file content but only an address of the file on storage - if the API doesn't let you pass content in another way, you have to use temporary files, no other option.

At best, you can make sure that they are deleted after usage:

  • create them in /tmp using File.createTempFile
  • mark them as deleteOnExit if current procedure fails and/or
  • call delete on file in finally block

If you are using Cats Effect it would make sense to do something like:

val withTempFile = Resource.make[F, File] {
  F.delay(File.createTempFile)
} { file =>
  F.delay(file.delete)
}

withTempFile.use { file =>
  // operation in F
}

If you are using plain Scala, loan pattern can work out:

def withTempFile(thunk: File => A): A = {
  val tmpFile = File.createTempFile
  try {
    thunk(tmpFile)
  } finally {
    tmpFile.delete
  }
}

withTempFile { file =>
  // operation
}

Once you have temporary file that is (almost) certain to be deleted you can write to it and pass the file reference to your service.

If you want to avoid using a tmp file on disk you can consider something like RAM disk if you have the possibility. The bottom line is - if API doesn't let you use Array[Byte] and only accepts File you have to write this file on disk. Or look for a different service provider/API.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.