Adrien Gorrell
Adrien Gorrell

Reputation: 1319

Create a temporary java.io.File from byte[]

I must use an existing method that is like saveAttachment(Attachment attachment) where Attachment has a File attribute.

My problem is that I'm retrieving a byte[] and I want to save it using this method. How can I have a "local" File just for saving ?

Sorry if my question is dumb, I don't know much about Files in Java.

Upvotes: 29

Views: 55327

Answers (3)

TheKojuEffect
TheKojuEffect

Reputation: 21101

File tempFile = File.createTempFile(prefix, suffix, null);
FileOutputStream fos = new FileOutputStream(tempFile);
fos.write(byteArray);

Check out related docs:

File.createTempFile(prefix, suffix, directory);

Upvotes: 56

user2474948
user2474948

Reputation:

Reading All Bytes or Lines from a File

Path file = ...;
byte[] fileArray;
fileArray = Files.readAllBytes(file);

Writing All Bytes or Lines to a File

Path file = ...;
byte[] buf = ...;
Files.write(file, buf);

Upvotes: 5

Kayaman
Kayaman

Reputation: 73568

You're in luck.

File.createTempFile(String prefix, String suffix)

Creates a file in the default temp directory of the OS, where it's guaranteed you can write to.

Upvotes: 3

Related Questions