Saturday 12 March 2022

Java: Write byte array to a file

Below snippet writes the byte array to a file.

public static void writeToFile(byte[] dataToWrite, String outputFilePath) throws IOException {

	File outputFile = new File(outputFilePath);

	if (outputFile.getParentFile() != null) {
		outputFile.getParentFile().mkdirs();
	}

	try (FileOutputStream fos = new FileOutputStream(outputFilePath)) {
		fos.write(dataToWrite);
	}
}

 

 


Find the below working application.

 

WriteByteArrayToAFile.java

 

package com.sample.app;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;

public class WriteByteArrayToAFile {

	public static void writeToFile(byte[] dataToWrite, String outputFilePath) throws IOException {

		File outputFile = new File(outputFilePath);

		if (outputFile.getParentFile() != null) {
			outputFile.getParentFile().mkdirs();
		}

		try (FileOutputStream fos = new FileOutputStream(outputFilePath)) {
			fos.write(dataToWrite);
		}
	}

	public static void main(String[] args) throws IOException {
		String str = "Hello World";
		byte[] bytes = str.getBytes();

		writeToFile(bytes, "/Users/Shared/demo1/demo2/a.txt");
	}

}




You may like

File programs in Java

Get file name from absolute path

Count number of lines in a file

Download file from Internet using Java

Get the content of resource file as string

Copy the content of file to other location

No comments:

Post a Comment