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.
1 Answer
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
/tmpusingFile.createTempFile - mark them as
deleteOnExitif current procedure fails and/or - call
deleteonfileinfinallyblock
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.
valwithout creating a new file