Home > Java > javaTutorial > How do I Save a String to a Text File in Java?

How do I Save a String to a Text File in Java?

DDD
Release: 2024-12-11 13:04:11
Original
201 people have browsed it

How do I Save a String to a Text File in Java?

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");
Copy after login

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);
Copy after login

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();
Copy after login

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);
}
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template