9

I have an array of bytes

bytes[] doc

How can I create an instance of new File from those bytes?

9
  • 1
    Are you asking how to write a binary file to the file system? Commented May 8, 2014 at 5:50
  • Google for "Java IO tutorial". Commented May 8, 2014 at 5:51
  • Java Tutorial: Basic IO Commented May 8, 2014 at 5:51
  • 3
    @Bob: a File in memory is not something that exists. A file is on a file system. An instance of File doesn't contain any byte. It's just a a file path. And reading fro a file will always read from the file system, not from a byte array in memory. If you want to read from a byte array in memory, then use a ByteArrayInputStream. If not, tell us what you actually want to achieve. Commented May 8, 2014 at 5:59
  • 1
    The comments on this question make it extremely clear that what the OP wants is NOT what is asked in that other question. To anybody who bothers to read, it is obvious that this is not a duplicate. Why was it closed? Commented May 8, 2014 at 20:37

3 Answers 3

21
 try (FileOutputStream fileOuputStream = new FileOutputStream("filename")){
    fileOuputStream.write(byteArray);
 }
Sign up to request clarification or add additional context in comments.

2 Comments

You'd better close in a finally block, or better, use a try-with-resources statement. Your code will leak resources in case of an exception.
But the OP wrote: "No, just [an] instance of File in memory. I do not need to write it to [the] filesystem."
15

Try this:

Files.write(Paths.get("filename"), bytes);

1 Comment

But the OP wrote: "No, just [an] instance of File in memory. I do not need to write it to [the] filesystem."
5

A simple program that will write a byte[] into a file.

import java.io.File;
import java.io.FileOutputStream;

public class BytesToFile {

    public static void main(String[] args) {

        byte[] demBytes = null; // Instead of null, specify your bytes here.

        File outputFile = new File("LOCATION TO FILE");

        try ( FileOutputStream outputStream = new FileOutputStream(outputFile); ) {

            outputStream.write(demBytes);  // Write the bytes and you're done.

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}

Note: The try-catch statement requires a Java version >= 1.7. Remember to change the bytes from null to correspond to your byte array.

3 Comments

About 10 minutes before you posted this, the OP posted a comment explaining that this was not what he wanted.
took 10 minutes to write on the iPad :( i guess someone else will find it useful.
But the OP wrote: "No, just [an] instance of File in memory. I do not need to write it to [the] filesystem."

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.