Java Tutorial #1 – How to Write to a Text File (Part 1)

Courtesy Note: If you found this tutorial helpful, please take a few moments to comment below!

The following notable Java built-in classes are used in this tutorial:

1. “BufferedWriter”
2. “FileWriter”

Java Tutorial #1 – How to Write to a Text File

This will be a very simple code example on writing content to a file. This example writes a simple integer to a text file. It creates a file named “numBlinks.txt”, and outputs “100” to the text file.

// Author: Jourdan Bul-lalayao
// Purpose: Small program that logs generated data into a text file


public class DataLog {

  private int numBlinks;

  public DataLog() {
    numBlinks = 0;

  // Function: gen()
  // Purpose: Generate data to be logged
  public void gen() {

  // Function: log()
  // Purpose: Log data into a .txt file
  public void log() {

    // Make file for # of blinks
    File blinkLog = new File("numBlinks.txt");

    // Try/catch statement necessary for FileWriter
    try {
      BufferedWriter writer = new BufferedWriter(new FileWriter(blinkLog));

      // If we don't use String.valueOf, it will output string equivalent of numBlinks.

      // ALWAYS CLOSE THE WRITER, file will be empty if you don't close it
    } catch (IOException e) {
      System.out.println("Unable to write to file!");

  public static void main(String[] args) {

    DataLog log = new DataLog();

    // Generate data
    for (int i = 0; i < 100; i++) {

    // Log data into txt file

Questions? Feedback? Please leave a comment below!