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?
In Java 11 the
java.nio.file.Files
class was extended by two new utility methods to write a string into a file (see JavaDoc here and here). In the simplest case it is now a one-liner:With the optional Varargs parameter, further options, such as appending to a existing file or automatically creating a non-existent file can be set (see JavaDoc here).
Use
FileUtils.writeStringToFile()
from Apache Commons IO. No need to reinvent this particular wheel.Just did something similar in my project. Use FileWriter will simplify part of your job. And here you can find nice tutorial.
It's better to close the writer/outputstream in a finally block, just in case something happen
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.
Use this, it is very readable: