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
DDDOriginal
2024-12-28 09:14:10125browse

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");
  1. Write the String:
out.println(text);
  1. Close the PrintWriter:
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!

Statement:
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