Write File Java Using BufferedOutputStream

Write File Java Using BufferedOutputStream

In this example we will write data to the file using BufferedOutputStream. This class implements buffered output stream and by getting an output stream java program can write bytes to the output stream as shown below:

Java Class:

package com.javahonk;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.OutputStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

import org.apache.commons.io.FileUtils;

public class WriteFileUsingBufferedOutputStream {
	
	private final static String WRITE_TO_FILE_NAME = "C:\\JavaHonk\\File\\WriteToFile.txt";
	private final static String READ_TO_FILE_NAME = "C:\\JavaHonk\\File\\JavaHonk.txt";

	public static void main(String args[]) throws IOException {

		File writeToFile = new File(WRITE_TO_FILE_NAME);
		File readFromFile = new File(READ_TO_FILE_NAME);
		Path writeFilePath = Paths.get(WRITE_TO_FILE_NAME);
		String inputFileStringRepresentation = FileUtils.readFileToString(readFromFile, "UTF-8");
		
		if (!writeToFile.exists()) {
			writeToFile.createNewFile();
		}
	
		byte data[] = inputFileStringRepresentation.getBytes();
		try (OutputStream out = new BufferedOutputStream(Files.newOutputStream(writeFilePath))) {
		    out.write(data, 0, data.length);
		} catch (IOException ioException) {
		    System.err.println(ioException);
		}		
		
	}
	

}

Output:

Write File Java Using BufferedOutputStream

For more information about BufferedOutputStream please see this oracle API link 

Leave a Reply

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