What is the best way to write a String to a file in Java?

In Java, I have some text stored in a String variable called "text", which comes from a text field.

How can I efficiently write this string to a file in Java while ensuring proper file handling and minimal performance overhead?

Writing a string to a file in Java is a common task, and luckily, there are multiple ways to do it depending on your needs.

If you’re looking for a quick and straightforward way to write a string to a file, you can use Files.write(). This method is part of Java NIO, which provides efficient file handling.

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

public class WriteToFile {
    public static void main(String[] args) throws IOException {
        String text = "Hello, this is a test string!";
        Path filePath = Path.of("output.txt");

        Files.write(filePath, text.getBytes(), StandardOpenOption.CREATE, StandardOpenOption.WRITE);
        System.out.println("String written to file successfully!");
    }
}

:white_check_mark: Why use this?

Minimal code – Just one method call. Efficient – Uses Java’s NIO for better performance. Auto-closes resources – No need for manual closing like in FileWriter.

If you prefer an older but still reliable way to write a string to a file in Java, FileWriter is a good choice.

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

public class WriteToFile {
    public static void main(String[] args) {
        String text = "Hello, this is a test string!";
        
        try (FileWriter writer = new FileWriter("output.txt")) {
            writer.write(text);
            System.out.println("String written to file successfully!");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

If you need to write a large amount of text efficiently, BufferedWriter is a better option than FileWriter because it buffers the data, reducing the number of write operations.

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

public class WriteToFile {
    public static void main(String[] args) {
        String text = "Hello, this is a test string!";
        
        try (BufferedWriter writer = new BufferedWriter(new FileWriter("output.txt"))) {
            writer.write(text);
            System.out.println("String written to file successfully!");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

:white_check_mark: Why use this?

  • Efficient for writing large text files
  • Reduces disk I/O operations
  • Uses a buffer, so writing is faster than FileWriter alone