Saving a String to a Text File in Java
Problem:
How can you save the contents of a String variable (text) to a text file using Java?
Solution:
Using a PrintWriter
To save a String to a text file, you can use a PrintWriter object. Here's how:
PrintWriter out = new PrintWriter("filename.txt");
out.println(text);
out.close();
Using a try-with-resources Statement (Java 7 )
If you're using Java 7 or later, you can use the try-with-resources statement to automatically close the PrintStream when you're done:
try (PrintWriter out = new PrintWriter("filename.txt")) { out.println(text); }
Handling Exceptions:
Note that both approaches require you to handle the FileNotFoundException that may be thrown when opening the file.
The above is the detailed content of How Can I Save a String to a Text File in Java?. For more information, please follow other related articles on the PHP Chinese website!