How to Write File in Java

1. Overview

In this example, we will use BufferedWriter class to write the file. There are another Stream Output classes to write file but in this example, we will focus on frequently used BufferedWriter.
Java BufferedWriter class is used to provide buffering for Writer instances. It makes the performance fast. It inherits Writer class. The buffering characters are used for providing the efficient writing of single arrays, characters, and strings.

2. Write File Example

import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * This Java program demonstrates how to write file in Java.
 * @author javaguides.net
 */

public class WriteFileExample {
 private static final Logger LOGGER = LoggerFactory.getLogger(WriteFileExample.class);

 public static void main(String[] args) {
  writeFile();
 }

 // Write file using BufferedWriter
 public static void writeFile() {
  try (BufferedWriter bw = new BufferedWriter(
    new FileWriter("C:/workspace/sample.txt"))) {
   String content = "This is the content to write into file\n";
   bw.write(content);
  } catch (IOException e) {
   LOGGER.error(e.getMessage());
  }
 }
}

3. Reference

Comments