adam bien's blog

Java 11: Write a String To File 📎

With the method writeString introduced in Java 11, writing a String to a file takes a single line:

import static org.junit.jupiter.api.Assertions.assertEquals;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import org.junit.jupiter.api.Test;

//...

@Test
public void writeString() throws IOException {
    Path fileName = Path.of("celebration.txt");
    String content  = "duke is 25";
    Files.writeString(fileName, content);
    
    String actual = Files.readString(fileName);
    assertEquals(content,actual);
}