Write Byte Array To File

Write Byte Array To File

Below example show you how to write byte array to file using BufferedOutputStream java:

package com.fileio;

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

public class WriteByteArrayInToFile {
	public static void main(String[] args) {

		String strFileName = "C:\\JavaHorn\\Test Files\\Test.txt";
		BufferedOutputStream bos = null;

		try {
			// create an object of FileOutputStream
			FileOutputStream fos = new FileOutputStream(new File(strFileName));

			// create an object of BufferedOutputStream
			bos = new BufferedOutputStream(fos);

			String str = "BufferedOutputStream Example";

			/*
			 * To write byte array to file use, public void write(byte[] b)
			 * method of BufferedOutputStream class.
			 */
			System.out.println("Writing byte array to file");

			bos.write(str.getBytes());

			System.out.println("File written done");
		} catch (FileNotFoundException fnfe) {
			System.out.println(fnfe);
		} catch (IOException ioe) {
			System.out.println(ioe);
		} finally {
			if (bos != null) {
				try {

					// flush the BufferedOutputStream
					bos.flush();

					// close the BufferedOutputStream
					bos.close();

				} catch (Exception e) {
				}
			}
		}

	}
}

Leave a Reply

Your email address will not be published. Required fields are marked *