28

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.

Adrien Gorrell
  • 1,291
  • 3
  • 14
  • 28
  • 1
    From where you are retreiving byte[]? Where you want to save your data? Need more context & explanation – Piotr Müller Sep 25 '13 at 13:38
  • 1
    I save the data using a method that itself uses alfresco community sdk to store the file, so I can't change the way it is saved. And I retrieve the byte from a web-service that does not provide other information. For those reasons I didn't give more details in my question. – Adrien Gorrell Sep 25 '13 at 13:54

3 Answers3

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

Check out related docs:

File.createTempFile(prefix, suffix, directory);

TheKojuEffect
  • 20,103
  • 19
  • 89
  • 125
5

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);
3

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.

Kayaman
  • 72,141
  • 5
  • 83
  • 121