Home >Java >javaTutorial >How to Save a Java String to a Text File?
Saving a String to a Text File in Java
In Java, the String class provides a myriad of methods for manipulating and storing text. One common task is to save the contents of a String variable to a text file for persistent storage. Here's how to accomplish this:
Using a PrintWriter
The PrintWriter class offers a convenient way to write text to a file. To utilize this approach, follow these steps:
PrintWriter out = new PrintWriter("filename.txt");
out.println(text);
out.close();
Using a Try-With-Resources Statement (Java 7 only)
From Java 7 onwards, you can employ the try-with-resources statement to simplify the process. This statement automatically closes resources when exiting the block.
try (PrintWriter out = new PrintWriter("filename.txt")) { out.println(text); }
Note that you'll still need to explicitly handle the FileNotFoundException.
The above is the detailed content of How to Save a Java String to a Text File?. For more information, please follow other related articles on the PHP Chinese website!