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

Java

Java Problem Overview


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

Java Solutions


Solution 1 - 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.

Solution 2 - Java

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

Solution 3 - Java

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

Solution 4 - Java

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

Solution 5 - Java

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

Solution 6 - Java

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.

Solution 7 - Java

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

Solution 8 - Java

         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.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questionrover12View Question on Stackoverflow
Solution 1 - JavaMichael Lloyd Lee mlkView Answer on Stackoverflow
Solution 2 - JavalutzView Answer on Stackoverflow
Solution 3 - JavaSebastian RedlView Answer on Stackoverflow
Solution 4 - JavaKevin BourrillionView Answer on Stackoverflow
Solution 5 - JavaJuanZeView Answer on Stackoverflow
Solution 6 - JavaBrian AgnewView Answer on Stackoverflow
Solution 7 - JavaslottView Answer on Stackoverflow
Solution 8 - JavaTomView Answer on Stackoverflow