How can I write a byte array to a file in Java?

How to write a byte array to a file in Java?


As Sebastian Redl points out the most straight forward now java.nio.file.Files.write. Details for this can be found in the Reading, Writing, and Creating Files tutorial.


Old answer: FileOutputStream.write(byte[]) would be the most straight forward. What is the data you want to write?

The tutorials for Java IO system may be of some use to you.


You can use IOUtils.write(byte[] data, OutputStream output) from Apache Commons IO.

KeyGenerator kgen = KeyGenerator.getInstance("AES");
kgen.init(128);
SecretKey key = kgen.generateKey();
byte[] encoded = key.getEncoded();
FileOutputStream output = new FileOutputStream(new File("target-file"));
IOUtils.write(encoded, output);

As of Java 1.7, there's a new way: java.nio.file.Files.write

import java.nio.file.Files;
import java.nio.file.Paths;

KeyGenerator kgen = KeyGenerator.getInstance("AES");
kgen.init(128);
SecretKey key = kgen.generateKey();
byte[] encoded = key.getEncoded();
Files.write(Paths.get("target-file"), encoded);

Java 1.7 also resolves the embarrassment that Kevin describes: reading a file is now:

byte[] data = Files.readAllBytes(Paths.get("source-file"));

A commenter asked "why use a third-party library for this?" The answer is that it's way too much of a pain to do it yourself. Here's an example of how to properly do the inverse operation of reading a byte array from a file (sorry, this is just the code I had readily available, and it's not like I want the asker to actually paste and use this code anyway):

public static byte[] toByteArray(File file) throws IOException { 
   ByteArrayOutputStream out = new ByteArrayOutputStream(); 
   boolean threw = true; 
   InputStream in = new FileInputStream(file); 
   try { 
     byte[] buf = new byte[BUF_SIZE]; 
     long total = 0; 
     while (true) { 
       int r = in.read(buf); 
       if (r == -1) {
         break; 
       }
       out.write(buf, 0, r); 
     } 
     threw = false; 
   } finally { 
     try { 
       in.close(); 
     } catch (IOException e) { 
       if (threw) { 
         log.warn("IOException thrown while closing", e); 
       } else {
         throw e;
       } 
     } 
   } 
   return out.toByteArray(); 
 }

Everyone ought to be thoroughly appalled by what a pain that is.

Use Good Libraries. I, unsurprisingly, recommend Guava's Files.write(byte[], File).