What is Files.writeString in Java?
In Java 11, a new method called Files.writeString was introduced to write
Method signature
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
Arguments
-
Path: Path object points to the file in which the string is to be written. -
CharSequence: A sequence of characters. All the characters of theCharSequenceare written on the file, including line separators. No additional characters are added. -
CharSet: The charset used to encode characters into bytes. While writing theCharSequence, all characters are encoded into bytes using .the specified charset by default, UTF-8 -
OpenOption: We can specify how a file should be opened using theOpenOptionargument. For example, we can specify: “Open a file in Append mode, Open a file as a new file.” If we don’t send anyOpenOptionthen:- 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 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:
- Created a Path object to point the file to be written (
test.txt). - Called the
Files.writeStringwith:-
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.