You are currently viewing Java Programming 101: How to Write Text to a File

Java Programming 101: How to Write Text to a File

In Java programming, writing text to a file is a fundamental task that often arises in various software development projects. Whether you’re working with data storage, logging, or generating reports, the ability to write text to a file is essential. In this blog post, we will explore how to write text to a file in Java.

The program creates a file named “memo.txt” and uses a PrintWriter object to write three lines of text to it. The Java program and the created file are located in the same directory.

When the code is finished writing to the file, it utilizes a try-with-resources statement to automatically close the PrintWriter object. This is a good practice to make sure that resources are properly released when they are no longer required.

import java.io.File;
import java.io.FileNotFoundException;
import java.io.PrintWriter;

public class Main {

    public static void main(String[] args) {

        String pathname = "memo.txt";

        File file = new File(pathname);

        try (PrintWriter writer = new PrintWriter(file)) {

            // write three lines of text to the file
            writer.println("Line 1");
            writer.println("Line 2");
            writer.println("Line 3");

            System.out.printf("Text written to file %s.\n", pathname);

        } catch (FileNotFoundException e) {

            // handle file not found exception
            System.out.println(e.getMessage());

        }

    }

}

If the file “memo.txt” cannot be created or opened for writing, a FileNotFoundException is thrown and its message is printed to the console. I hope that’s been informative to you. If you wish to learn more about Java, please subscribe to our newsletter today and continue your Java learning journey with us!

Leave a Reply