805

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?

24 Answers 24

814

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 close the output stream when you've finished writing.

out.close()

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.

12
  • 4
    @Justin, you could also pass an absolute path (e.g. "/tmp/filename.txt") to the FileOutputStream constructor, to save the file anywhere you want
    – Jonik
    Jun 28, 2009 at 8:54
  • 8
    Btw, this could be simplified using the convenience constructors PrintStream has had since 1.5. This would suffice: PrintStream out = new PrintStream("filename.txt");
    – Jonik
    Jun 28, 2009 at 16:22
  • 10
    Need to close that file though at some point...? codecodex.com/wiki/ASCII_file_save#Java
    – JStrahl
    Jun 22, 2012 at 8:03
  • 3
    You want to use try{} catch(){}finally{}, where in finally{} you close the file if it is not null.
    – Benas
    Aug 13, 2014 at 13:34
  • 26
    In java8 you can try(PrintStream ps = new PrintStream("filename")) { ps.println(out); } this will handle close for you Feb 6, 2015 at 16:14
277

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

static void writeStringToFile(File file, String data, Charset charset) 

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

FileUtils.writeStringToFile(new File("test.txt"), "Hello File", Charset.forName("UTF-8"));

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

3
  • 10
    Just a minor correction, the second fragment should read: FileUtils.writeStringToFile(new File("test.txt"), "Hello File");
    – pm_labs
    Feb 9, 2012 at 0:31
  • 3
    For those of us who prefer Guava, it can do this too.
    – Jonik
    Dec 29, 2013 at 15:50
  • 16
    The function is now deprecated, you should add the default charset --> FileUtils.writeStringToFile(new File("test.txt"), "Hello File", forName("UTF-8")); Nov 9, 2017 at 8:10
139

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

6
  • 4
    In case someone later wondered, the encoding would be the platform standard. Nov 29, 2015 at 14:12
  • 13
    content.getBytes(StandardCharsets.UTF_8) can be used to explicitly define the encoding.
    – John29
    Apr 28, 2016 at 20:43
  • 1
    Note that StandardOpenOption.CREATE is not the default one StandardOpenOption.CREATE and StandardOpenOption.TRUNCATE_EXISTING is the default. To use the default just remove the third parameter.
    – Tinus Tate
    Jan 10, 2019 at 14:57
  • Please see Tinus Tate's comment! What is the process to edit this example? I wonder how many thousands of people have taken this example as-is only to find that they have unexpected results when they overwrite a file with a shorter string. As Tinus indicates, TRUNCATE_EXISTING is crucial unless you fully understand and have an actual reason for not wanting to truncate the existing file when overwriting with a shorter string. Oct 8, 2019 at 23:46
  • 2
    In java 11 you can simply put a String as a second parameter! Hooray! Nov 20, 2019 at 10:22
115

Take a look at the Java File API

a quick example:

try (PrintStream out = new PrintStream(new FileOutputStream("filename.txt"))) {
    out.print(text);
}
5
  • @XP1 I know, that's a great improvement. I've used Lombok for this in Java 6: just go @Cleanup new FileOutputStream(...) and you're done.
    – Jorn
    Sep 4, 2011 at 9:31
  • 8
    Don't forget to call out.flush(); then out.close();
    – Alex Byrth
    Jan 11, 2016 at 1:16
  • @AlexByrth why should he? Sep 11, 2018 at 16:51
  • 1
    Large files are recorded in the background (another thread) and take time to record. Calling flush () ensures that everything has been written on the next line, synchronizing the operation. But this is optional, but good practice if you handle large files, as logs.
    – Alex Byrth
    Sep 12, 2018 at 18:10
  • 2
    Note that out.close() already flushes the stream, which means it is not necessary to call out.flush().
    – hjk321
    Dec 31, 2019 at 5:38
83

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)
    {
    }
}
4
  • 4
    Removing all try/catch and simplify it I'm also able to do it in one line just by doing the: (new BufferedWriter( new FileWriter( filename))).write(str); Jun 27, 2009 at 19:46
  • Wrapping a FileWriter in a BufferedWriter is superfluous when you're writing out the entire file in a single write() call. Nov 22, 2011 at 6:08
  • 2
    It seems that .close() doesn't throw (at least in Java 7?), is the last trycatch perhaps redundant?
    – Kos
    Jun 14, 2012 at 10:43
  • 17
    Swallowing exceptions like that is going to make life hard for you when exceptions really do occur. At the very least you should rethrow them: throw new RuntimeException(e); Feb 11, 2013 at 19:05
70

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

8
  • 20
    I couldn't disagree more. These libraries are there so we don't introduce subtle bugs in such a simple solution.
    – skaffman
    Jun 27, 2009 at 20:04
  • 3
    No, obviously not. I'm only disagreeing that your solution might not be the first thing I'd throw at someone who's a beginner Java programmer. You aren't suggesting that you've never written such a thing, are you?
    – duffymo
    Jun 27, 2009 at 21:25
  • 8
    I have, yes, but that's before I found commons-io. Since finding that, I've never written that sort of thing by hand, even in a one-class project. If I'd known about it from day one, I'd have used it from day one.
    – skaffman
    Jun 27, 2009 at 21:40
  • 5
    Exactly, but you're an experienced developer. Your bio says your a JBOSS/Spring user, but certainly you wouldn't have been up to either one in your first "Hello, World" effort. I'm not disagreeing with the proper use of libraries. I'm saying that people attempting a language for the first time should try to know it at its bottom, even if that means doing things that they'll discard later on when they're experienced and know better.
    – duffymo
    Jun 27, 2009 at 21:45
  • 2
    I implemented this without commons and got a less than obvious exception thrown. I then implemented this using commons and it told me exactly what was wrong. Moral of the story: why live in the dark ages if you don't have to?
    – SilentNot
    Apr 14, 2014 at 17:42
54

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);
2
  • 3
    This needs more upvotes. The answer gets buried in the amount of answers provided to this question, yet it is superior to many of them. E.g. only a minimal amount of lines is required, there is also no dependency on Apache Commons. Mar 29, 2021 at 9:27
  • I second above comment, this is an elegant solution !!
    – sarath
    Nov 21, 2022 at 14:50
25

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

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
}
5
  • 3
    If you're using Guava, there is also Charsets.UTF-8.
    – florian
    Oct 30, 2015 at 14:07
  • 3
    @florian: It's Charsets.UTF_8 actually
    – Tim Büthe
    Mar 29, 2016 at 17:59
  • The parent folder must exist. Example: destination.mkdirs(). Jun 19, 2018 at 8:19
  • 2
    Files.write(CharSequence from, File to, Charset charset) is deprecated in guava 26.0. Jul 18, 2019 at 20:10
  • Modern Guava alternative to deprecated Files.write: Files.asCharSink(file, charset).write(text)
    – Vadzim
    Apr 7, 2020 at 20:43
14

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);
}
3
  • A word to the wise - this will create a new file if it isn't there, but will overwrite the characters of the existing file if it is. If the new data is smaller, that will mean you probably create a corrupted file. Ask me how I know!
    – Chris Rae
    Feb 5, 2017 at 23:29
  • Ok, how do you know?
    – ojblass
    Mar 10, 2018 at 2:58
  • 1
    Just use Files.write(targetPath, bytes); to overwrite the file then. It will work as expected. Mar 10, 2018 at 12:09
14

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();
        }
    }
}
1
  • 1
    Files.write(path, byte[]) will use UTF-8 encoding. String.getBytes() uses the default platform encoding. So this is a potential issue. Use string.getBytes(StandardCharsets.UTF_8)!
    – rmuller
    Jun 15, 2019 at 7:04
13

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>
12

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);
2
  • It's also a copy of an existing answer. :c Jul 21, 2016 at 18:14
  • 2
    sorry but i didn't invent java8 , i am not the only one that use this line . but it is not a copy past from other answers to the same question
    – Ran Adler
    Jul 24, 2016 at 5:37
11
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.

11

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

Using org.apache.commons.io.FileUtils:

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

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.

2
  • @Eric Leschinski : thank you for making my answer more professional (i also assumed this was exactly what the OP wanted since this is what actually most people wants,just dump the text and replace it) Aug 15, 2013 at 17:36
  • 2
    Once the original question has been answered and the OP is satisfied and long-gone, pages like this serve only as a useful artifact to people who land here from a Google search. I landed on this page in order to create a mini text appender to a file. So it's good to speak to the entire audience rather than the OP after the OP has moved on. Aug 15, 2013 at 20:19
6

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);
    }
  }
6
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);
    }
}
2
  • 3
    While this code snippet may be the solution, including an explanation really helps to improve the quality of your post. Remember that you are answering the question for readers in the future, and those people might not know the reasons for your code suggestion.
    – Johan
    May 10, 2019 at 10:55
  • 1
    close() may never be called. Please, improve your answer adding the proper error case handling. Apr 27, 2020 at 20:21
4

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

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.

0

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

    });
0

I have published a library that saves files, and handles everything with one line of code only, you can find it here along with its documentation

Github repository

and the answer to your question is so easy

String path = FileSaver
        .get()
        .save(string.getBytes(),"file.txt");
-1

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;
}
1
  • 2
    Please add proper error case handling closing all opened resources and propogating exceptions Apr 27, 2020 at 20:22

Not the answer you're looking for? Browse other questions tagged or ask your own question.