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);
}

Comments:

Post a Comment:
  • HTML Syntax: NOT allowed
...the last 150 posts
...the last 10 comments
License