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?
Use Apache Commons IO api. Its simple
Use API as
Maven Dependency
Take a look at the Java File API
a quick example:
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...
I think the best way is using
Files.write(Path path, Iterable<? extends CharSequence> lines, OpenOption... options)
:See javadoc:
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 abyte[]
array, thustext.getBytes()
is not required, which is a bit cleaner I think.If you only care about pushing one block of text to file, this will overwrite it each time.
This example allows the user to select a file using a file chooser.
If you wish to keep the carriage return characters from the string into a file here is an code example: