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

1,312,207

Solution 1

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.

Solution 2

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.

Solution 3

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

Solution 4

Take a look at the Java File API

a quick example:

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

Solution 5

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)
    {
    }
}
Share:
1,312,207
Justin White
Author by

Justin White

Updated on December 29, 2021

Comments

  • Justin White
    Justin White over 2 years

    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?

  • Artem Barger
    Artem Barger almost 15 years
    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);
  • skaffman
    skaffman almost 15 years
    I couldn't disagree more. These libraries are there so we don't introduce subtle bugs in such a simple solution.
  • Justin White
    Justin White almost 15 years
    What's exception handling? Where will this file be saved?
  • skaffman
    skaffman almost 15 years
    Would you suggest that he go back and re-implement java.file.IO and java.io.PrintStream in raw C? Of course not. You use the java.io abstractions, and save your effort for real problems. And Commons IO is a better abstraction than java.io when it comes to this particular problem.
  • duffymo
    duffymo almost 15 years
    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?
  • skaffman
    skaffman almost 15 years
    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.
  • Jeremy Smyth
    Jeremy Smyth almost 15 years
    it'll be saved in the current directory, whatever that is as far as the JVM is concerned. Exception handling is the try{} catch(){} stuff you see in other answers :)
  • duffymo
    duffymo almost 15 years
    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.
  • Jonik
    Jonik almost 15 years
    @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
    Jonik almost 15 years
    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
    Jonik almost 15 years
    Futhermore, as we're outputting text, PrintWriter would be more appropriate, and just as convenient. From PrintStream javadocs: "The PrintWriter class should be used in situations that require writing characters rather than bytes."
  • Jorn
    Jorn over 12 years
    @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.
  • Adrian Pronk
    Adrian Pronk over 12 years
    Wrapping a FileWriter in a BufferedWriter is superfluous when you're writing out the entire file in a single write() call.
  • pm_labs
    pm_labs about 12 years
    Just a minor correction, the second fragment should read: FileUtils.writeStringToFile(new File("test.txt"), "Hello File");
  • Kos
    Kos almost 12 years
    It seems that .close() doesn't throw (at least in Java 7?), is the last trycatch perhaps redundant?
  • JStrahl
    JStrahl almost 12 years
    Need to close that file though at some point...? codecodex.com/wiki/ASCII_file_save#Java
  • lisak
    lisak over 11 years
    new PrintWriter(file).println(output); results in 0 byte file. Output is a string of 6000 chars...No matter if the file exists already or not...
  • Roger Keays
    Roger Keays about 11 years
    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);
  • Jeremy Smyth
    Jeremy Smyth almost 11 years
    @Sloin @Devolus Did you make sure to call out.close()? It writes an empty file if the PrintWriter is garbage-collected before it's flushed or closed, but if you close() it correctly it writes the file.
  • bhathiya-perera
    bhathiya-perera over 10 years
    @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)
  • Eric Leschinski
    Eric Leschinski over 10 years
    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.
  • Jonik
    Jonik over 10 years
    For those of us who prefer Guava, it can do this too.
  • SilentNot
    SilentNot about 10 years
    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?
  • Mr_and_Mrs_D
    Mr_and_Mrs_D about 10 years
    @duffymo: well Commons way now moved to Java 7 anyway :D
  • Benas
    Benas over 9 years
    You want to use try{} catch(){}finally{}, where in finally{} you close the file if it is not null.
  • Anton Chikin
    Anton Chikin about 9 years
    In java8 you can try(PrintStream ps = new PrintStream("filename")) { ps.println(out); } this will handle close for you
  • yegeniy
    yegeniy about 9 years
    Regarding @AntonChikin comment above: you can also do this in Java 7
  • codewing
    codewing over 8 years
    Can you guys try to print a very long text? When I do it it with a text containing 8 855 704 chars and 197 247 line breaks it only writes 197 127 lines into the file. (Using the code from above with a try catch ofc) -> Using a FileWriter solved my problem. use the .write(String) function there...
  • florian
    florian over 8 years
    If you're using Guava, there is also Charsets.UTF-8.
  • Haakon Løtveit
    Haakon Løtveit over 8 years
    In case someone later wondered, the encoding would be the platform standard.
  • Alex Byrth
    Alex Byrth over 8 years
    Don't forget to call out.flush(); then out.close();
  • Tim Büthe
    Tim Büthe about 8 years
    @florian: It's Charsets.UTF_8 actually
  • John29
    John29 about 8 years
    content.getBytes(StandardCharsets.UTF_8) can be used to explicitly define the encoding.
  • james.garriss
    james.garriss almost 8 years
    It's also a copy of an existing answer. :c
  • Ran Adler
    Ran Adler almost 8 years
    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
  • Chit Khine
    Chit Khine over 7 years
    how about the effienciency of this code? I am writing a million lines of string to the file using printWriter for half a day and it is still running.
  • Chris Rae
    Chris Rae over 7 years
    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!
  • Paul Fournel
    Paul Fournel over 6 years
    The function is now deprecated, you should add the default charset --> FileUtils.writeStringToFile(new File("test.txt"), "Hello File", forName("UTF-8"));
  • ojblass
    ojblass about 6 years
    Ok, how do you know?
  • BullyWiiPlaza
    BullyWiiPlaza about 6 years
    Just use Files.write(targetPath, bytes); to overwrite the file then. It will work as expected.
  • AlikElzin-kilaka
    AlikElzin-kilaka almost 6 years
    The parent folder must exist. Example: destination.mkdirs().
  • Andrew Tobilko
    Andrew Tobilko over 5 years
    @AlexByrth why should he?
  • Alex Byrth
    Alex Byrth over 5 years
    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.
  • Tinus Tate
    Tinus Tate over 5 years
    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.
  • Johan
    Johan almost 5 years
    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.
  • rmuller
    rmuller almost 5 years
    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)!
  • Sergio A.
    Sergio A. almost 5 years
    +1 for using a well-known library. We still need answers "from the bottom" and oriented to "experienced" developers
  • Donald Duck
    Donald Duck almost 5 years
    Files.write(CharSequence from, File to, Charset charset) is deprecated in guava 26.0.
  • jch
    jch over 4 years
    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.
  • Dennis Gloss
    Dennis Gloss over 4 years
    In java 11 you can simply put a String as a second parameter! Hooray!
  • hjk321
    hjk321 over 4 years
    Note that out.close() already flushes the stream, which means it is not necessary to call out.flush().
  • Vadzim
    Vadzim about 4 years
    Modern Guava alternative to deprecated Files.write: Files.asCharSink(file, charset).write(text)
  • Boris Brodski
    Boris Brodski about 4 years
    close() may never be called. Please, improve your answer adding the proper error case handling.
  • Boris Brodski
    Boris Brodski about 4 years
    Please add proper error case handling closing all opened resources and propogating exceptions
  • Koenigsberg
    Koenigsberg about 3 years
    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.