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

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

    In Java 11 the java.nio.file.Files class was extended by two new utility methods to write a string into a file. The first method (see JavaDoc here) uses the charset UTF-8 as default:

    Files.writeString(Path.of("my", "path"), "My String");
    

    And the second method (see JavaDoc here) allows to specify an individual charset:

    Files.writeString(Path.of("my", "path"), "My String", StandardCharset.ISO_8859_1);
    

    Both methods have an optional Varargs parameter for setting file handling options (see JavaDoc here). The following example would create a non-existing file or append the string to an existing one:

    Files.writeString(Path.of("my", "path"), "String to append", StandardOpenOption.CREATE, StandardOpenOption.APPEND);
    

提交回复
热议问题