Use Apache Commons IO
FileUtils.writeByteArrayToFile(new File("pathname"), myByteArray)
Or, if you insist on making work for yourself...
try (FileOutputStream fos = new FileOutputStream("pathname")) {
fos.write(myByteArray);
//fos.close(); There is no more need for this line since you had created the instance of "fos" inside the try. And this will automatically close the OutputStream
}
Answer from bmargulies on Stack OverflowUse Apache Commons IO
FileUtils.writeByteArrayToFile(new File("pathname"), myByteArray)
Or, if you insist on making work for yourself...
try (FileOutputStream fos = new FileOutputStream("pathname")) {
fos.write(myByteArray);
//fos.close(); There is no more need for this line since you had created the instance of "fos" inside the try. And this will automatically close the OutputStream
}
Without any libraries:
try (FileOutputStream stream = new FileOutputStream(path)) {
stream.write(bytes);
}
With Google Guava:
Files.write(bytes, new File(path));
With Apache Commons:
FileUtils.writeByteArrayToFile(new File(path), bytes);
All of these strategies require that you catch an IOException at some point too.
Videos
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);
You can use existing collections Like e.g. List to maintain List of byte[] and transfer it
List<byte[]> list = new ArrayList<byte[]>();
list.add("HI".getBytes());
list.add("BYE".getBytes());
ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream(
"test.txt"));
out.writeObject(list);
ObjectInputStream in = new ObjectInputStream(new FileInputStream(
"test.txt"));
List<byte[]> byteList = (List<byte[]>) in.readObject();
//if you want to add to list you will need to add to byteList and write it again
for (byte[] bytes : byteList) {
System.out.println(new String(bytes));
}
Output:
HI
BYE
Another option is use RandomAccessFile. Which will not force you to read complete file and you can skip the data that you don't want to read.
DataOutputStream dataOutStream = new DataOutputStream(
new FileOutputStream("test1"));
int numberOfChunks = 2;
dataOutStream.writeInt(numberOfChunks);// Write number of chunks first
byte[] firstChunk = "HI".getBytes();
dataOutStream.writeInt(firstChunk.length);//Write length of array a small custom protocol
dataOutStream.write(firstChunk);//Write byte array
byte[] secondChunk = "BYE".getBytes();
dataOutStream.writeInt(secondChunk.length);//Write length of array
dataOutStream.write(secondChunk);//Write byte array
RandomAccessFile randomAccessFile = new RandomAccessFile("test1", "r");
int chunksRead = randomAccessFile.readInt();
for (int i = 0; i < chunksRead; i++) {
int size = randomAccessFile.readInt();
if (i == 1)// means we only want to read last chunk
{
byte[] bytes = new byte[size];
randomAccessFile.read(bytes, 0, bytes.length);
System.out.println(new String(bytes));
}
randomAccessFile.seek(4+(i+1)*size+4*(i+1));//From start so 4 int + i* size+ 4* i ie. size of i
}
Output:
BYE
You have to described your data in your encoding. i.e. add some metadata.
For example, the length of the array, then the data of the array.
This is called serialization.
Array of int: length(4 bytes), data[0] (4 bytes), data[1] (4 bytes), data[2] (4 bytes)
Writing the file byte by byte will incur the overhead of a system call for every single byte.
Fortunately, there's an overload of write that takes an entire byte[] and writes it out with far fewer system calls:
try (FileOutputStream fileOutputStream = new FileOutputStream(outputFile)) {
fileOutputStream.write(responseBytes);
}
In your current code, you're writing to the file using a loop:
for (int ii=0; ii<responseBytes.length; ii++) {
fileOutputStream.write(responseBytes, ii, 1);
}
This will write one byte at a time to the file output stream. Each call to fileOutputStream.write() incurs overhead because of method invocation and possibly disk I/O operations. Instead of writing one byte at a time, you can write the entire byte array in a single call:
// Write the entire byte array at once - much faster
try (FileOutputStream fileOutputStream = new FileOutputStream(outputFile){
fileOutputStream.write(responseBytes);
}
However, for even better performance, wrap your FileOutputStream in a BufferedOutputStream as follows:
import java.io.BufferedOutputStream;
// ...
try (BufferedOutputStream bufferedOutputStream = new BufferedOutputStream(new FileOutputStream(outputFile))) {
bufferedOutputStream.write(responseBytes);
}
Finally, I think that you have to go even beyond that and try not to read the entire file into memory, which can cause high memory consumption. you can directly stream the object into file skipping load it into memory.. Here How you can stream it directly into files skipping memory:
// Get the response input stream from S3
ResponseInputStream<GetObjectResponse> s3InputStream = s3Client.getObject(request);
// Define the path to the output file
File outputFile = new File(downloadPath);
try (InputStream inputStream = s3InputStream;
OutputStream outputStream = new BufferedOutputStream(new FileOutputStream(outputFile))) {
byte[] buffer = new byte[8192]; // Buffer size can be adjusted
int bytesRead;
// Read and write in chunks
while ((bytesRead = inputStream.read(buffer)) != -1) {
outputStream.write(buffer, 0, bytesRead);
}
} catch (IOException e) {
e.printStackTrace();
// Handle exceptions appropriately
}