Java 11 – Files writeString() API

Learn to write a string into file in Java using Files.writeString(path, string, options) method. This API has been introduced in Java 11.

1. Files writeString() methods

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
  • First method writes all content to a file, using the UTF-8 charset.
  • First method is equivalent to writeString(path, string, StandardCharsets.UTF_8, options).
  • Second method does the same with with only using the specified charset.
  • 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);

			//Verify 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 comments section.

Happy Learning !!

Comments are closed for this article!

About Us

HowToDoInJava provides tutorials and how-to guides on Java and related technologies.

It also shares the best practices, algorithms & solutions and frequently asked interview questions.