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

后端 未结 24 1064
不知归路
不知归路 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:28

    Basically the same answer as here, but easy to copy/paste, and it just works ;-)

      import java.io.FileWriter;
    
      public void saveToFile(String data, String filename) {
        try (
          FileWriter fw = new FileWriter(filename)) {
          fw.write(data);
        } catch (Exception e) {
          throw new RuntimeException(e);
        }
      }
    

提交回复
热议问题