How to write a byte array to a file in Java?
-
can you put some code and show what exactly you want to write to the file? – Koray Tugay Mar 07 '15 at 09:27
8 Answers
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.

- 1
- 1

- 14,561
- 3
- 44
- 81
-
byte[] encoded = key.getEncoded(); i need to write encoded to a text file – rover12 Nov 20 '09 at 11:11
-
KeyGenerator kgen = KeyGenerator.getInstance("AES"); kgen.init(128); SecretKey key = kgen.generateKey(); byte[] encoded = key.getEncoded(); – rover12 Nov 20 '09 at 11:14
-
-
+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...) – Andreas Dolk Nov 20 '09 at 11:47
-
You should wrap the FileOutputStream in a BufferedOutputStream as suggested by @JuanZe. Performance is much better. – Sam Barnum Nov 20 '09 at 14:43
-
Using `FileOutputStream` works under Android, while `java.nio.file` doesn't exist. – Brent Faust Nov 19 '14 at 20:31
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);

- 19,209
- 22
- 79
- 122
-
65
-
5
-
@GauravAgarwal Not in her/his original question (which they should have updated!), but see the first and third comment here: http://stackoverflow.com/questions/1769776/how-can-i-write-a-byte-array-to-a-file-in-java#comments-1769788 – Liam Jan 10 '14 at 22:19
-
2
-
+1 for FileOutputStream output = new FileOutputStream(new File("target-file")); – bizzr3 Jul 11 '14 at 10:15
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"));

- 2,563
- 26
- 39

- 69,373
- 8
- 123
- 157
-
8This 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
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).

- 40,336
- 12
- 74
- 87
-
2I 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
-
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
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...

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

- 268,207
- 37
- 334
- 440
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);
}
}

- 3,266
- 1
- 35
- 30
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.

- 1
- 1