Write Text to a File in Java

Tags: Java File Java IO Java NIO

Introduction

In this tutorial we are going to learn how to write text to a text file in a Java application. By different Java example programs we will explore different approaches to write a String into a text file using Java core classes.

Using Java NIO Files.write() static method

Following program to create a new file named test.txt and write text using Files.write() method.

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;

public class FilesWriteExample1 {
    public static void main(String... args) {
        try {
            String fileName = "test.txt";
            Path filePath = Paths.get(fileName);
            String contentToAppendToFile = "Simple Solution";

            // Convert String into byte array and write to file
            Files.write(filePath, contentToAppendToFile.getBytes(), StandardOpenOption.CREATE);

        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

By using option StandardOpenOption.APPEND we can append text to an existing file.

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;

public class FilesWriteExample2 {
    public static void main(String... args) {
        try {
            String fileName = "test.txt";
            Path filePath = Paths.get(fileName);
            String contentToAppendToFile = "Simple Solution";

            // Append to existing file.
            Files.write(filePath, contentToAppendToFile.getBytes(), StandardOpenOption.APPEND);

        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

The above append example will throw an error message when the file we are trying to write does not exist.

java.nio.file.NoSuchFileException: test.txt
	at sun.nio.fs.WindowsException.translateToIOException(WindowsException.java:79)
	at sun.nio.fs.WindowsException.rethrowAsIOException(WindowsException.java:97)
	at sun.nio.fs.WindowsException.rethrowAsIOException(WindowsException.java:102)
	at sun.nio.fs.WindowsFileSystemProvider.newByteChannel(WindowsFileSystemProvider.java:230)
	at java.nio.file.spi.FileSystemProvider.newOutputStream(FileSystemProvider.java:434)
	at java.nio.file.Files.newOutputStream(Files.java:216)
	at java.nio.file.Files.write(Files.java:3292)
	at FilesWriteExample2.main(FilesWriteExample2.java:15)

To fix this error and make the application create a new file when it doesn’t exist and append when there is a file then we can add the option StandardOpenOption.CREATE as the following example.

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;

public class FilesWriteExample3 {
    public static void main(String... args) {
        try {
            String fileName = "test.txt";
            Path filePath = Paths.get(fileName);
            String contentToAppendToFile = "Simple Solution";

            // use 2 options to create file if it doesn't exist
            // and append if file exist.
            Files.write(filePath, contentToAppendToFile.getBytes(), StandardOpenOption.CREATE, StandardOpenOption.APPEND);

        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

Files class also provides a method to allow writing a list of String.

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;
import java.util.ArrayList;
import java.util.List;

public class FilesWriteExample4 {
    public static void main(String... args) {
        try {
            String fileName = "test.txt";
            Path filePath = Paths.get(fileName);

            List<String> contentToWrite = new ArrayList<>();
            contentToWrite.add("Line 1");
            contentToWrite.add("Line 2");
            contentToWrite.add("Line 3");

            // write a list of String
            Files.write(filePath, contentToWrite, StandardOpenOption.CREATE, StandardOpenOption.APPEND);
            
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

Using Java NIO Files.newBufferedWriter() static method

Following Java program to show how to use Files.newBufferedWriter() to open existing files for writing or creating new files for writing text.

import java.io.BufferedWriter;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;

public class FilesNewBufferedWriterExample {
    public static void main(String... args) {
        try {
            String fileName = "test.txt";
            Path filePath = Paths.get(fileName);

            BufferedWriter bufferedWriter = Files.newBufferedWriter(filePath, StandardOpenOption.CREATE, StandardOpenOption.APPEND);

            bufferedWriter.write("Line 1");
            bufferedWriter.newLine();
            bufferedWriter.write("Line 2");
            bufferedWriter.newLine();
            bufferedWriter.write("Line 3");

            bufferedWriter.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

Using Java IO FileWriter

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

public class FileWriterExample1 {
    public static void main(String... args) {
        String fileName = "test.txt";

        // use FileWriter to write text file
        try(FileWriter fileWriter = new FileWriter(fileName)) {
            fileWriter.write("Line 1\n");
            fileWriter.write("Line 2\n");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

Using Java IO BufferedWriter and FileWriter

Using BufferedWriter to handle large file.

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

public class FileWriterExample2 {
    public static void main(String... args) {
        String fileName = "test.txt";

        // use FileWriter with BufferedWriter
        try(FileWriter fileWriter = new FileWriter(fileName);
            BufferedWriter bufferedWriter = new BufferedWriter(fileWriter)) {
            bufferedWriter.write("Line 1");
            bufferedWriter.newLine();
            bufferedWriter.write("Line 2");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

Using Java IO PrintWriter

import java.io.IOException;
import java.io.PrintWriter;

public class PrintWriterExample {
    public static void main(String... args) {
        String fileName = "test.txt";
        
        // use PrintWriter to write text file
        try(PrintWriter printWriter = new PrintWriter(fileName)) {
            printWriter.write("Line 1");
            printWriter.write("\n");
            printWriter.write("Line 2");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

Using Java IO FileOutputStream, OutputStreamWriter and BufferedWriter

import java.io.BufferedWriter;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;

public class BufferedWriterExample {
    public static void main(String... args) {
        String fileName = "test.txt";

        try(FileOutputStream fileOutputStream = new FileOutputStream(fileName);
            OutputStreamWriter outputStreamWriter = new OutputStreamWriter(fileOutputStream);
            BufferedWriter bufferedWriter = new BufferedWriter(outputStreamWriter)) {
            bufferedWriter.write("Line 1");
            bufferedWriter.newLine();
            bufferedWriter.write("Line 2");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

Happy Coding 😊

Get File Size in Java

Get Absolute File Path of a File in Java