72

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

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
rover12
  • 2,806
  • 7
  • 27
  • 28

8 Answers8

74

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.

Community
  • 1
  • 1
Michael Lloyd Lee mlk
  • 14,561
  • 3
  • 44
  • 81
40

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);
David says Reinstate Monica
  • 19,209
  • 22
  • 79
  • 122
35

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"));
Jeff Terrell Ph.D.
  • 2,563
  • 26
  • 39
Sebastian Redl
  • 69,373
  • 8
  • 123
  • 157
  • 8
    This is probably the recommended way nowadays. All the `SecretKey` stuff is not needed; just call `Files.write()`. Thanks Sebastian! – barfuin Aug 15 '13 at 18:51
16

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).

Kevin Bourrillion
  • 40,336
  • 12
  • 74
  • 87
  • 2
    I am appalled by what a pain that is, but also that this sort of thing isn't in the standard library. We're not talking about an obscure file format, but moving bytes from memory to disk. – Jim Pivarski Jul 10 '13 at 22:16
  • 2
    best answer: Guava's Files.write(byte[], File). – jan Mar 21 '14 at 12:22
  • I'll take this answer over libraries! You may be interested in this question: https://stackoverflow.com/questions/70074875/read-write-bytes-to-and-from-a-file-using-only-java-io – Nerdy Bunz Nov 23 '21 at 03:24
12

To write a byte array to a file use the method

public void write(byte[] b) throws IOException

from BufferedOutputStream class.

java.io.BufferedOutputStream implements a buffered output stream. By setting up such an output stream, an application can write bytes to the underlying output stream without necessarily causing a call to the underlying system for each byte written.

For your example you need something like:

String filename= "C:/SO/SOBufferedOutputStreamAnswer";
BufferedOutputStream bos = null;
try {
//create an object of FileOutputStream
FileOutputStream fos = new FileOutputStream(new File(filename));

//create an object of BufferedOutputStream
bos = new BufferedOutputStream(fos);

KeyGenerator kgen = KeyGenerator.getInstance("AES"); 
kgen.init(128); 
SecretKey key = kgen.generateKey(); 
byte[] encoded = key.getEncoded();

bos.write(encoded);

} 
// catch and handle exceptions...
JuanZe
  • 8,007
  • 44
  • 58
  • 1
    +1 for mentioning BufferedOutputStream. You should ALWAYS wrap a FileOutputStream in a BufferedOutputStream, performance is much better. – Sam Barnum Nov 20 '09 at 14:41
  • 4
    If all you want to write to the file is a 16 byte key, wrapping the FileOutputStream in a BufferedOutputStream is probably slower than writing the data directly to the FileOutputStream. – jarnbjo Nov 20 '09 at 15:08
  • @SamBarnum Can you elaborate? Why is wrapping the FOS in a BOS faster? – john_science Dec 15 '12 at 23:41
  • It depends on which write() method you use. If you're writing a byte at a time (or in small chunks), that results in a lot of disk activity. If your disk is network mounted, this can be catastrophic. – Sam Barnum Dec 16 '12 at 23:43
  • Well he did say "can be" catastrophic. Man, damn devs always got to be nitpicky and argumentative... :P – User May 05 '17 at 02:44
7

Apache Commons IO Utils has a FileUtils.writeByteArrayToFile() method. Note that if you're doing any file/IO work then the Apache Commons IO library will do a lot of work for you.

Brian Agnew
  • 268,207
  • 37
  • 334
  • 440
4

No need for external libs to bloat things - especially when working with Android. Here is a native solution that does the trick. This is a pice of code from an app that stores a byte array as an image file.

    // Byte array with image data.
    final byte[] imageData = params[0];

    // Write bytes to tmp file.
    final File tmpImageFile = new File(ApplicationContext.getInstance().getCacheDir(), "scan.jpg");
    FileOutputStream tmpOutputStream = null;
    try {
        tmpOutputStream = new FileOutputStream(tmpImageFile);
        tmpOutputStream.write(imageData);
        Log.d(TAG, "File successfully written to tmp file");
    }
    catch (FileNotFoundException e) {
        Log.e(TAG, "FileNotFoundException: " + e);
        return null;
    }
    catch (IOException e) {
        Log.e(TAG, "IOException: " + e);
        return null;
    }
    finally {
        if(tmpOutputStream != null)
            try {
                tmpOutputStream.close();
            } catch (IOException e) {
                Log.e(TAG, "IOException: " + e);
            }
    }
slott
  • 3,266
  • 1
  • 35
  • 30
0
         File file = ...
         byte[] data = ...
         try{
            FileOutputStream fos = FileOutputStream(file);
            fos.write(data);
            fos.flush();
            fos.close();
         }catch(Exception e){
          }

but if the bytes array length is more than 1024 you should use loop to write the data.

Tom
  • 1
  • 1