How do I save a String to a text file using Java?

后端 未结 24 1105
不知归路
不知归路 2020-11-22 04:18

In Java, I have text from a text field in a String variable called \"text\".

How can I save the contents of the \"text\" variable to a file?

24条回答
  •  误落风尘
    2020-11-22 04:55

    If you're simply outputting text, rather than any binary data, the following will work:

    PrintWriter out = new PrintWriter("filename.txt");
    

    Then, write your String to it, just like you would to any output stream:

    out.println(text);
    

    You'll need exception handling, as ever. Be sure to call out.close() when you've finished writing.

    If you are using Java 7 or later, you can use the "try-with-resources statement" which will automatically close your PrintStream when you are done with it (ie exit the block) like so:

    try (PrintWriter out = new PrintWriter("filename.txt")) {
        out.println(text);
    }
    

    You will still need to explicitly throw the java.io.FileNotFoundException as before.

提交回复
热议问题