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

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();
        }
    }
}