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 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?
You could do this:
Apache Commons IO contains some great methods for doing this, in particular FileUtils contains the following method:
which allows you to write text to a file in one method call:
You might also want to consider specifying the encoding for the file as well.
Using
Java 7
:If you're simply outputting text, rather than any binary data, the following will work:
Then, write your String to it, just like you would to any output stream:
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:You will still need to explicitly throw the
java.io.FileNotFoundException
as before.