73

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

1
  • can you put some code and show what exactly you want to write to the file? Commented Mar 7, 2015 at 9:27

8 Answers 8

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.

Sign up to request clarification or add additional context in comments.

6 Comments

byte[] encoded = key.getEncoded(); i need to write encoded to a text file
KeyGenerator kgen = KeyGenerator.getInstance("AES"); kgen.init(128); SecretKey key = kgen.generateKey(); byte[] encoded = key.getEncoded();
Then simply use FileOutputStream.
+1 for mentioning tutorials... (you'd received even a +2 if you mentioned www.google.com - OK, that was nasty, but it's not rovers first question...)
You should wrap the FileOutputStream in a BufferedOutputStream as suggested by @JuanZe. Performance is much better.
|
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);

5 Comments

Why add a 3rd party library for this?
The OP does not ask AES encoding of the byteArray.
@GauravAgarwal Not in her/his original question (which they should have updated!), but see the first and third comment here: stackoverflow.com/questions/1769776/…
@lutz is doing PR for Apache Commons.
+1 for FileOutputStream output = new FileOutputStream(new File("target-file"));
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"));

1 Comment

This is probably the recommended way nowadays. All the SecretKey stuff is not needed; just call Files.write(). Thanks Sebastian!
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).

3 Comments

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.
best answer: Guava's Files.write(byte[], File).
I'll take this answer over libraries! You may be interested in this question: stackoverflow.com/questions/70074875/…
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...

5 Comments

+1 for mentioning BufferedOutputStream. You should ALWAYS wrap a FileOutputStream in a BufferedOutputStream, performance is much better.
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.
@SamBarnum Can you elaborate? Why is wrapping the FOS in a BOS faster?
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.
Well he did say "can be" catastrophic. Man, damn devs always got to be nitpicky and argumentative... :P
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.

1 Comment

Link is dead (Jim).
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);
            }
    }

Comments

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.