How do I save a String to a text file using Java?

8 Answers

Apache Commons IO contains some great methods for doing this, in particular FileUtils contains the following method:

static void writeStringToFile(File file, String data) 

which allows you to write text to a file in one method call:

FileUtils.writeStringToFile(new File("test.txt"), "Hello File");

You might also want to consider specifying the encoding for the file as well.


In Java, I have text from a text field in a String variable called "text".

How can I save the contents of the "text" variable to a file?

In case if you need create text file based on one single string:

import java.nio.file.Files;
import java.nio.file.Paths;

public class StringWriteSample {
    public static void main(String[] args) {
        String text = "This is text to be saved in file";

        try {
            Files.write(Paths.get("my-file.txt"), text.getBytes());
        } catch (IOException e) {

Using Java 7:

public static void writeToFile(String text, String targetFilePath) throws IOException
    Path targetPath = Paths.get(targetFilePath);
    byte[] bytes = text.getBytes(StandardCharsets.UTF_8);
    Files.write(targetPath, bytes, StandardOpenOption.CREATE);

Use this, it is very readable:

import java.nio.file.Files;
import java.nio.file.Paths;

Files.write(Paths.get(path), lines.getBytes(), StandardOpenOption.WRITE);

Take a look at the Java File API

a quick example:

try (PrintStream out = new PrintStream(new FileOutputStream("filename.txt"))) {

Use FileUtils.writeStringToFile() from Apache Commons IO. No need to reinvent this particular wheel.

Use Apache Commons IO api. Its simple

Use API as

 FileUtils.writeStringToFile(new File("FileNameToWrite.txt"), "stringToWrite");

Maven Dependency


You can use the ArrayList to put all the contents of the TextArea for exemple, and send as parameter by calling the save, as the writer just wrote string lines, then we use the "for" line by line to write our ArrayList in the end we will be content TextArea in txt file. if something does not make sense, I'm sorry is google translator and I who do not speak English.

Watch the Windows Notepad, it does not always jump lines, and shows all in one line, use Wordpad ok.

private void SaveActionPerformed(java.awt.event.ActionEvent evt) {

String NameFile = Name.getText();
ArrayList< String > Text = new ArrayList< String >();


SaveFile(NameFile, Text);


public void SaveFile(String name, ArrayList< String> message) {

path = "C:\\Users\\Paulo Brito\\Desktop\\" + name + ".txt";

File file1 = new File(path);

try {

    if (!file1.exists()) {


    File[] files = file1.listFiles();

    FileWriter fw = new FileWriter(file1, true);

    BufferedWriter bw = new BufferedWriter(fw);

    for (int i = 0; i < message.size(); i++) {



    FileReader fr = new FileReader(file1);

    BufferedReader br = new BufferedReader(fr);

    fw = new FileWriter(file1, true);

    bw = new BufferedWriter(fw);

    while (br.ready()) {

        String line = br.readLine();




} catch (IOException ex) {
    JOptionPane.showMessageDialog(null, "Error in" + ex);        


If you only care about pushing one block of text to file, this will overwrite it each time.

JFileChooser chooser = new JFileChooser();
int returnVal = chooser.showSaveDialog(this);
if (returnVal == JFileChooser.APPROVE_OPTION) {
    FileOutputStream stream = null;
    PrintStream out = null;
    try {
        File file = chooser.getSelectedFile();
        stream = new FileOutputStream(file); 
        String text = "Your String goes here";
        out = new PrintStream(stream);
        out.print(text);                  //This will overwrite existing contents

    } catch (Exception ex) {
        //do something
    } finally {
        try {
            if(stream!=null) stream.close();
            if(out!=null) out.close();
        } catch (Exception ex) {
            //do something

This example allows the user to select a file using a file chooser.