How do I save a String to a text file using Java?
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)
{
}
}
Justin White
Updated on December 29, 2021Comments
-
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 almost 15 yearsRemoving 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 almost 15 yearsI couldn't disagree more. These libraries are there so we don't introduce subtle bugs in such a simple solution.
-
Justin White almost 15 yearsWhat's exception handling? Where will this file be saved?
-
skaffman almost 15 yearsWould 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 almost 15 yearsNo, 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 almost 15 yearsI 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 almost 15 yearsit'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 almost 15 yearsExactly, 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 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 almost 15 yearsBtw, this could be simplified using the convenience constructors PrintStream has had since 1.5. This would suffice: PrintStream out = new PrintStream("filename.txt");
-
Jonik almost 15 yearsFuthermore, 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 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 over 12 yearsWrapping a FileWriter in a BufferedWriter is superfluous when you're writing out the entire file in a single
write()
call. -
pm_labs about 12 yearsJust a minor correction, the second fragment should read: FileUtils.writeStringToFile(new File("test.txt"), "Hello File");
-
Kos almost 12 yearsIt seems that
.close()
doesn't throw (at least in Java 7?), is the last trycatch perhaps redundant? -
JStrahl almost 12 yearsNeed to close that file though at some point...? codecodex.com/wiki/ASCII_file_save#Java
-
lisak over 11 yearsnew 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 about 11 yearsSwallowing 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 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 youclose()
it correctly it writes the file. -
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 over 10 yearsOnce 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 over 10 yearsFor those of us who prefer Guava, it can do this too.
-
SilentNot about 10 yearsI 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 about 10 years@duffymo: well Commons way now moved to Java 7 anyway :D
-
Benas over 9 yearsYou want to use try{} catch(){}finally{}, where in finally{} you close the file if it is not null.
-
Anton Chikin about 9 yearsIn java8 you can try(PrintStream ps = new PrintStream("filename")) { ps.println(out); } this will handle close for you
-
yegeniy about 9 yearsRegarding @AntonChikin comment above: you can also do this in Java 7
-
codewing over 8 yearsCan 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 over 8 yearsIf you're using Guava, there is also
Charsets.UTF-8
. -
Haakon Løtveit over 8 yearsIn case someone later wondered, the encoding would be the platform standard.
-
Alex Byrth over 8 yearsDon't forget to call out.flush(); then out.close();
-
Tim Büthe about 8 years@florian: It's
Charsets.UTF_8
actually -
John29 about 8 years
content.getBytes(StandardCharsets.UTF_8)
can be used to explicitly define the encoding. -
james.garriss almost 8 yearsIt's also a copy of an existing answer. :c
-
Ran Adler almost 8 yearssorry 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 over 7 yearshow 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 over 7 yearsA 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 over 6 yearsThe function is now deprecated, you should add the default charset -->
FileUtils.writeStringToFile(new File("test.txt"), "Hello File", forName("UTF-8"));
-
ojblass about 6 yearsOk, how do you know?
-
BullyWiiPlaza about 6 yearsJust use
Files.write(targetPath, bytes);
to overwrite the file then. It will work as expected. -
AlikElzin-kilaka almost 6 yearsThe parent folder must exist. Example: destination.mkdirs().
-
Andrew Tobilko over 5 years@AlexByrth why should he?
-
Alex Byrth over 5 yearsLarge 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 over 5 yearsNote 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 almost 5 yearsWhile 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 almost 5 yearsFiles.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. almost 5 years+1 for using a well-known library. We still need answers "from the bottom" and oriented to "experienced" developers
-
Donald Duck almost 5 yearsFiles.write(CharSequence from, File to, Charset charset) is deprecated in guava 26.0.
-
jch over 4 yearsPlease 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 over 4 yearsIn java 11 you can simply put a String as a second parameter! Hooray!
-
hjk321 over 4 yearsNote that out.close() already flushes the stream, which means it is not necessary to call out.flush().
-
Vadzim about 4 yearsModern Guava alternative to deprecated Files.write:
Files.asCharSink(file, charset).write(text)
-
Boris Brodski about 4 yearsclose() may never be called. Please, improve your answer adding the proper error case handling.
-
Boris Brodski about 4 yearsPlease add proper error case handling closing all opened resources and propogating exceptions
-
Koenigsberg about 3 yearsThis 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.