Write Large File Java Using BufferedWriter

Write Large File Java Using BufferedWriter

In this sample java class you will see how to read data from file and write to another file using BufferedWriter.  This can be use to write very large data set:

Java Class:

package com.javahonk;

import java.io.BufferedWriter;
import java.io.File;
import java.io.IOException;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.List;

public class WriteLargeFileUsingBufferedWriter {
	
	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";
	private final static Charset ENCODING = StandardCharsets.UTF_8;

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

		File writeToFile = new File(WRITE_TO_FILE_NAME);
		Path writeFilePath = Paths.get(WRITE_TO_FILE_NAME);
		Path readFilePath = Paths.get(READ_TO_FILE_NAME);
		
		if (!writeToFile.exists()) {
			writeToFile.createNewFile();
		}
		
		List<String> lines2 = Files.readAllLines(readFilePath, ENCODING);
		try (BufferedWriter writer = Files.newBufferedWriter(writeFilePath,ENCODING)) {
			for (String line : lines2) {
				writer.write(line);
				writer.newLine();
			}
		}	
		
	}
	

}

Output:

Write Large File Java Using BufferedWriter

For more information about BufferedWriter please read oracle documentation here

Leave a Reply

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