Learn to write a string into a file in Java using Files.writeString()
method. This API has been introduced in Java 11.
1. Files writeString() Method
The java.nio.file.Files
class has two overloaded static methods to write content to file.
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
- The first method writes all content to a file, using the UTF-8 charset.
- The first method is equivalent to
writeString(path, string, StandardCharsets.UTF_8, options)
. - The second method does the same but only using the specified charset.
- The
options
specifies how the file is opened.
2. Files writeString() Example
Java program to write String into a file using Files.writeString()
method.
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.Files;
import java.io.IOException;
import java.nio.file.StandardOpenOption;
public class Main {
public static void main(String[] args) {
Path filePath = Paths.get("C:/", "temp", "test.txt");
try {
//Write content to file
Files.writeString(filePath, "Hello World !!", StandardOpenOption.APPEND);
//Optionally verify the file content
String content = Files.readString(filePath);
System.out.println(content);
}
catch (IOException e) {
e.printStackTrace();
}
}
}
Program output.
Hello World !!
Where the file c:/temp/test.txt
is empty initially.
Drop me your questions in the comments section.
Happy Learning !!
Comments