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

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?

This question is related to java file file-io text-files

The answer is


If you wish to keep the carriage return characters from the string into a file here is an code example:

    jLabel1 = new JLabel("Enter SQL Statements or SQL Commands:");
    orderButton = new JButton("Execute");
    textArea = new JTextArea();
    ...


    // String captured from JTextArea()
    orderButton.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent ae) {
            // When Execute button is pressed
            String tempQuery = textArea.getText();
            tempQuery = tempQuery.replaceAll("\n", "\r\n");
            try (PrintStream out = new PrintStream(new FileOutputStream("C:/Temp/tempQuery.sql"))) {
                out.print(tempQuery);
            } catch (FileNotFoundException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            System.out.println(tempQuery);
        }

    });

Take a look at the Java File API

a quick example:

try (PrintStream out = new PrintStream(new FileOutputStream("filename.txt"))) {
    out.print(text);
}

Just did something similar in my project. Use FileWriter will simplify part of your job. And here you can find nice tutorial.

BufferedWriter writer = null;
try
{
    writer = new BufferedWriter( new FileWriter( yourfilename));
    writer.write( yourstring);

}
catch ( IOException e)
{
}
finally
{
    try
    {
        if ( writer != null)
        writer.close( );
    }
    catch ( IOException e)
    {
    }
}

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

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.


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

    Text.add(TextArea.getText());

    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()) {

            file1.createNewFile();
        }


        File[] files = file1.listFiles();


        FileWriter fw = new FileWriter(file1, true);

        BufferedWriter bw = new BufferedWriter(fw);

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

            bw.write(message.get(i));
            bw.newLine();
        }

        bw.close();
        fw.close();

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

            System.out.println(line);

            bw.write(line);
            bw.newLine();

        }
        br.close();
        fr.close();

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

import java.io.*;

private void stringToFile( String text, String fileName )
 {
 try
 {
    File file = new File( fileName );

    // if file doesnt exists, then create it 
    if ( ! file.exists( ) )
    {
        file.createNewFile( );
    }

    FileWriter fw = new FileWriter( file.getAbsoluteFile( ) );
    BufferedWriter bw = new BufferedWriter( fw );
    bw.write( text );
    bw.close( );
    //System.out.println("Done writing to " + fileName); //For testing 
 }
 catch( IOException e )
 {
 System.out.println("Error: " + e);
 e.printStackTrace( );
 }
} //End method stringToFile

You can insert this method into your classes. If you are using this method in a class with a main method, change this class to static by adding the static key word. Either way you will need to import java.io.* to make it work otherwise File, FileWriter and BufferedWriter will not be recognized.


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.


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


You can use the modify the code below to write your file from whatever class or function is handling the text. One wonders though why the world needs a new text editor...

import java.io.*;

public class Main {

    public static void main(String[] args) {

        try {
            String str = "SomeMoreTextIsHere";
            File newTextFile = new File("C:/thetextfile.txt");

            FileWriter fw = new FileWriter(newTextFile);
            fw.write(str);
            fw.close();

        } catch (IOException iox) {
            //do stuff with exception
            iox.printStackTrace();
        }
    }
}

It's better to close the writer/outputstream in a finally block, just in case something happen

finally{
   if(writer != null){
     try{
        writer.flush();
        writer.close();
     }
     catch(IOException ioe){
         ioe.printStackTrace();
     }
   }
}

My way is based on stream due to running on all Android versions and needs of fecthing resources such as URL/URI, any suggestion is welcome.

As far as concerned, streams (InputStream and OutputStream) transfer binary data, when developer goes to write a string to a stream, must first convert it to bytes, or in other words encode it.

public boolean writeStringToFile(File file, String string, Charset charset) {
    if (file == null) return false;
    if (string == null) return false;
    return writeBytesToFile(file, string.getBytes((charset == null) ? DEFAULT_CHARSET:charset));
}

public boolean writeBytesToFile(File file, byte[] data) {
    if (file == null) return false;
    if (data == null) return false;
    FileOutputStream fos;
    BufferedOutputStream bos;
    try {
        fos = new FileOutputStream(file);
        bos = new BufferedOutputStream(fos);
        bos.write(data, 0, data.length);
        bos.flush();
        bos.close();
        fos.close();
    } catch (IOException e) {
        e.printStackTrace();
        Logger.e("!!! IOException");
        return false;
    }
    return true;
}

If you're simply outputting text, rather than any binary data, the following will work:

PrintWriter out = new PrintWriter("filename.txt");

Then, write your String to it, just like you would to any output stream:

out.println(text);

You'll need exception handling, as ever. Be sure to call out.close() when you've finished writing.

If you are using Java 7 or later, you can use the "try-with-resources statement" which will automatically close your PrintStream when you are done with it (ie exit the block) like so:

try (PrintWriter out = new PrintWriter("filename.txt")) {
    out.println(text);
}

You will still need to explicitly throw the java.io.FileNotFoundException as before.


Using org.apache.commons.io.FileUtils:

FileUtils.writeStringToFile(new File("log.txt"), "my string", Charset.defaultCharset());

In Java 7 you can do this:

String content = "Hello File!";
String path = "C:/a.txt";
Files.write( Paths.get(path), content.getBytes());

There is more info here: http://www.drdobbs.com/jvm/java-se-7-new-file-io/231600403


You could do this:

import java.io.*;
import java.util.*;

class WriteText
{
    public static void main(String[] args)
    {   
        try {
            String text = "Your sample content to save in a text file.";
            BufferedWriter out = new BufferedWriter(new FileWriter("sample.txt"));
            out.write(text);
            out.close();
        }
        catch (IOException e)
        {
            System.out.println("Exception ");       
        }

        return ;
    }
};

private static void generateFile(String stringToWrite, String outputFile) {
    try {       
        FileWriter writer = new FileWriter(outputFile);
        writer.append(stringToWrite);
        writer.flush();
        writer.close();
        log.debug("New File is generated ==>"+outputFile);
    } catch (Exception exp) {
        log.error("Exception in generateFile ", exp);
    }
}

Basically the same answer as here, but easy to copy/paste, and it just works ;-)

  import java.io.FileWriter;

  public void saveToFile(String data, String filename) {
    try (
      FileWriter fw = new FileWriter(filename)) {
      fw.write(data);
    } catch (Exception e) {
      throw new RuntimeException(e);
    }
  }

In Java 11 the java.nio.file.Files class was extended by two new utility methods to write a string into a file. The first method (see JavaDoc here) uses the charset UTF-8 as default:

Files.writeString(Path.of("my", "path"), "My String");

And the second method (see JavaDoc here) allows to specify an individual charset:

Files.writeString(Path.of("my", "path"), "My String", StandardCharset.ISO_8859_1);

Both methods have an optional Varargs parameter for setting file handling options (see JavaDoc here). The following example would create a non-existing file or append the string to an existing one:

Files.writeString(Path.of("my", "path"), "String to append", StandardOpenOption.CREATE, StandardOpenOption.APPEND);

Use Apache Commons IO api. Its simple

Use API as

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

Maven Dependency

<dependency>
    <groupId>commons-io</groupId>
    <artifactId>commons-io</artifactId>
    <version>2.4</version>
</dependency>

I think the best way is using Files.write(Path path, Iterable<? extends CharSequence> lines, OpenOption... options):

String text = "content";
Path path = Paths.get("path", "to", "file");
Files.write(path, Arrays.asList(text));

See javadoc:

Write lines of text to a file. Each line is a char sequence and is written to the file in sequence with each line terminated by the platform's line separator, as defined by the system property line.separator. Characters are encoded into bytes using the specified charset.

The options parameter specifies how the the file is created or opened. If no options are present then this method works as if the CREATE, TRUNCATE_EXISTING, and WRITE options are present. In other words, it opens the file for writing, creating the file if it doesn't exist, or initially truncating an existing regular-file to a size of 0. The method ensures that the file is closed when all lines have been written (or an I/O error or other runtime exception is thrown). If an I/O error occurs then it may do so after the file has created or truncated, or after some bytes have been written to the file.

Please note. I see people have already answered with Java's built-in Files.write, but what's special in my answer which nobody seems to mention is the overloaded version of the method which takes an Iterable of CharSequence (i.e. String), instead of a byte[] array, thus text.getBytes() is not required, which is a bit cleaner I think.


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

import java.io.IOException;
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) {
            e.printStackTrace();
        }
    }
}

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

I prefer to rely on libraries whenever possible for this sort of operation. This makes me less likely to accidentally omit an important step (like mistake wolfsnipes made above). Some libraries are suggested above, but my favorite for this kind of thing is Google Guava. Guava has a class called Files which works nicely for this task:

// This is where the file goes.
File destination = new File("file.txt");
// This line isn't needed, but is really useful 
// if you're a beginner and don't know where your file is going to end up.
System.out.println(destination.getAbsolutePath());
try {
    Files.write(text, destination, Charset.forName("UTF-8"));
} catch (IOException e) {
    // Useful error handling here
}

Examples related to java

Under what circumstances can I call findViewById with an Options Menu / Action Bar item? How much should a function trust another function How to implement a simple scenario the OO way Two constructors How do I get some variable from another class in Java? this in equals method How to split a string in two and store it in a field How to do perspective fixing? String index out of range: 4 My eclipse won't open, i download the bundle pack it keeps saying error log

Examples related to file

Gradle - Move a folder from ABC to XYZ Difference between opening a file in binary vs text Angular: How to download a file from HttpClient? Python error message io.UnsupportedOperation: not readable java.io.FileNotFoundException: class path resource cannot be opened because it does not exist Writing JSON object to a JSON file with fs.writeFileSync How to read/write files in .Net Core? How to write to a CSV line by line? Writing a dictionary to a text file? What are the pros and cons of parquet format compared to other formats?

Examples related to file-io

Python, Pandas : write content of DataFrame into text File Saving response from Requests to file How to while loop until the end of a file in Python without checking for empty line? Getting "java.nio.file.AccessDeniedException" when trying to write to a folder How do I add a resources folder to my Java project in Eclipse Read and write a String from text file Python Pandas: How to read only first n rows of CSV files in? Open files in 'rt' and 'wt' modes How to write to a file without overwriting current contents? Write objects into file with Node.js

Examples related to text-files

How to edit a text file in my terminal Reading specific columns from a text file in python Read a local text file using Javascript Split text file into smaller multiple text file using command line How do I read a text file of about 2 GB? Java - How Can I Write My ArrayList to a file, and Read (load) that file to the original ArrayList? Copying from one text file to another using Python Getting all file names from a folder using C# Reading From A Text File - Batch How to import data from text file to mysql database