What is Files.writeString in Java?

In Java 11, a new method called Files.writeString was introduced to write CharSequencea readable sequence of char values into a file.

Method signature

writeString has two overloaded methods:

public static Path writeString​(Path path, CharSequence csq, OpenOption... options) throws IOException
public static Path writeString​(Path path, CharSequence csq, Charset cs, OpenOption... options) throws IOException

Arguments

  1. Path: Path object points to the file in which the string is to be written.

  2. CharSequence: A sequence of characters. All the characters of the CharSequence are written on the file, including line separators. No additional characters are added.

  3. CharSet: The charset used to encode characters into bytes. While writing the CharSequence, all characters are encoded into bytes using the specified charsetby default, UTF-8.

  4. 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:

    • If the file is not present, a new file is created and written on it.
    • If the file is present, old content will be overwritten.

Read more about OpenOption here.

Example

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 files
Files.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:

  • Created a Path object to point the file to be written (test.txt).
  • Called the 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.

Free Resources