In Java 11, a new method called Files.writeString
was introduced to write
writeString
has two overloaded methods:
public static Path writeString(Path path, CharSequence csq, OpenOption... options) throws IOExceptionpublic static Path writeString(Path path, CharSequence csq, Charset cs, OpenOption... options) throws IOException
Path
: Path object points to the file in which the string is to be written.
CharSequence
: A sequence of characters. All the characters of the CharSequence
are written on the file, including line separators. No additional characters are added.
CharSet
: The charset used to encode characters into bytes. While writing the CharSequence
, all characters are encoded into bytes using
OpenOption
: We can specify how a file should be opened using the OpenOption
argument. For example, we can specify: “Open a file in Append mode, Open a file as a new file.” If we don’t send any OpenOption
then:
Read more about OpenOption here.
import java.nio.file.Path;import java.nio.file.Paths;import java.nio.file.Files;import java.io.IOException;import java.nio.file.StandardOpenOption;import java.nio.charset.StandardCharsets;public class Main {public static void main(String[] args){Path filePath = Paths.get("./test.txt");try {// write content to the filesFiles.writeString(filePath, "\nEducative.io", StandardCharsets.UTF_8, StandardOpenOption.APPEND);System.out.println(Files.readString(filePath));} catch (IOException e) {e.printStackTrace();}}}
In the code above, we have:
test.txt
).Files.writeString
with:
File path.
Content to be written on the file (\nEducative.io
).
Charset to encode the characters(UTF-8
).
File open mode set to “APPEND”.
After executing the program, the Educative.io
text will be added to the test.txt
in a new line.
Execute and test the file here.