+91 81900 98289

Java Write Files

Files.writeString creates or replaces a file and writes the text. The parent folder must already exist. Files.createDirectories makes the folders when they might be missing.

writeString replaces the whole file. To add to the end, pass StandardOpenOption.APPEND and StandardOpenOption.CREATE. There is no undo after a replace.

Example

The sample prints the text that a write call would store, then prints how many characters that text contains.

public class Save { public static void main(String[] args) { String text = "Hello from Chennai"; System.out.println(text); System.out.println(text.length()); } }
On your machine, Files.writeString(Path.of("note.txt"), text) stores that same text. Open the file afterward and confirm the letters before you write a program that deletes anything.