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

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

    Apache Commons IO contains some great methods for doing this, in particular FileUtils contains the following method:

    static void writeStringToFile(File file, String data) 
    

    which allows you to write text to a file in one method call:

    FileUtils.writeStringToFile(new File("test.txt"), "Hello File");
    

    You might also want to consider specifying the encoding for the file as well.

提交回复
热议问题