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

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

DDD
Release: 2024-12-28 09:14:10
Original
113 people have browsed it

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

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:

  1. Create a PrintWriter:
PrintWriter out = new PrintWriter("filename.txt");
Copy after login
  1. Write the String:
out.println(text);
Copy after login
  1. Close the PrintWriter:
out.close();
Copy after login

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

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!

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