Saving a String to a Text File in Java
If you have a String variable containing text and need to store it in a file, Java offers a simple solution.
Creating a PrintWriter Object
To save the String to a text file, you first need to create a PrintWriter object:
PrintWriter out = new PrintWriter("filename.txt");
Writing the String
Once you have the PrintWriter object, you can use the println() method to write the String to the file:
out.println(text);
Closing the PrintWriter
After writing the String, you must close the PrintWriter object to ensure that the data is properly flushed to the file:
out.close();
Java 7 and Later: try-with-resources
For Java 7 and later, you can use the try-with-resources statement to automatically close the PrintWriter when you exit the block:
try (PrintWriter out = new PrintWriter("filename.txt")) { out.println(text); }
Exception Handling
Note that when creating the PrintWriter, you may need to handle the java.io.FileNotFoundException, which is thrown if the file does not exist or cannot be created.
The above is the detailed content of How do I Save a String to a Text File in Java?. For more information, please follow other related articles on the PHP Chinese website!