Write a text file
30 min · Beginner
Need help? Ask a tutor on WhatsApp (opens in a new tab)Writing a small text file is one call in Java: Files.writeString for a String, Files.write for a list of lines. The open options you pass decide what happens to a file that is already there: replace it, add to its end, or refuse to touch it.
Files.writeString and Files.write with lines
Files.writeString(path, text) writes one String to a file and closes it. It writes exactly the characters you give it, so you add \n yourself where you want a line break. It was added in Java 11 and writes UTF-8.
Example 1 · Files.writeString: one String into a file
import java.io.IOException;import java.nio.file.Files;import java.nio.file.Path;
public class WriteNoteDemo { public static void main(String[] args) throws IOException { Path note = Path.of("note.txt"); System.out.println("Exists before: " + Files.exists(note));
Files.writeString(note, "Library book due on 20 March.\nFine: Rs 2 per day.\n");
System.out.println("Exists after: " + Files.exists(note)); System.out.print(Files.readString(note));
Files.delete(note); }}Exists before: false Exists after: true Library book due on 20 March. Fine: Rs 2 per day.
What this code does
writeStringcreatednote.txtbecause it did not exist, wrote the text and closed the file, all in one call.- The
\ncharacters in the String become the line breaks in the file. Nothing is added: you write exactly the characters you pass.
Example 2 · Files.write: a list of lines
import java.io.IOException;import java.nio.file.Files;import java.nio.file.Path;import java.util.List;
public class StoreBillDemo { public static void main(String[] args) throws IOException { List<String> items = List.of("Pens x2 = 60", "Ruler x1 = 15", "Total = 75"); Path bill = Path.of("store-bill.txt");
Files.write(bill, items);
List<String> back = Files.readAllLines(bill); System.out.println("Lines written: " + back.size()); for (String line : back) { System.out.println("| " + line); } String text = Files.readString(bill); System.out.println("Last line has a line break: " + text.endsWith(System.lineSeparator()));
Files.delete(bill); }}Lines written: 3 | Pens x2 = 60 | Ruler x1 = 15 | Total = 75 Last line has a line break: true
What this code does
Files.write(path, lines)writes each item of the list and puts a line break after every one of them, the last one included.- The line break it adds is
System.lineSeparator():\r\non Windows,\non macOS and Linux. The Line endings lesson explains the difference.
Files.write(path, lines) takes a List<String> (or any Iterable) and writes each item as a line, with a line break after every item.
writeString. Files.write(path, "text") does not compile: write wants lines or a byte[].Default options: create and truncate
An open option is a setting that tells Java how to open the file. With no options, the write methods use three: CREATE (make the file if it is missing), TRUNCATE_EXISTING (empty it if it exists) and WRITE.
Example 3 · The default: an existing file is replaced
import java.io.IOException;import java.nio.file.Files;import java.nio.file.Path;
public class OverwriteDemo { public static void main(String[] args) throws IOException { Path name = Path.of("captain.txt"); Files.writeString(name, "Rahul Sharma\n"); Files.writeString(name, "Raj\n"); System.out.print("Captain file: " + Files.readString(name));
// Mistake: writing a log line by line with the default options Path log = Path.of("visitors.txt"); for (String visitor : new String[] {"Asha", "Ravi", "Meena"}) { Files.writeString(log, visitor + "\n"); } System.out.print("Visitors file: " + Files.readString(log));
Files.delete(name); Files.delete(log); }}Captain file: Raj Visitors file: Meena
What this code does
- The file is emptied first (truncated) and then written, so the longer old text
Rahul Sharmaleaves nothing behind. - In the loop, every call replaces the file again, so only the last visitor survives. A log needs
APPEND, shown next.
So the default is to overwrite. Writing Raj over Rahul Sharma leaves just Raj, not a mix of the two. This is right for a settings file or a report you rebuild each time, and wrong for a log.
Predict the output
Predict what the file holds
Read the options carefully: the default options matter.
Round 1 of 2
Three writes to the same file.
Appending with StandardOpenOption.APPEND
StandardOpenOption.APPEND writes at the end of the file and keeps everything already in it. Use it for logs: attendance entries, UPI payments, gate entries.
Example 4 · APPEND: add lines to the end of a log
import java.io.IOException;import java.nio.file.Files;import java.nio.file.NoSuchFileException;import java.nio.file.Path;import java.nio.file.StandardOpenOption;
public class AttendanceLogDemo { public static void main(String[] args) throws IOException { Path log = Path.of("attendance-log.txt"); Files.deleteIfExists(log);
String[] entries = {"09:05 Asha IN", "09:12 Ravi IN", "13:00 Asha OUT"}; for (String entry : entries) { Files.writeString(log, entry + "\n", StandardOpenOption.CREATE, StandardOpenOption.APPEND); } System.out.print(Files.readString(log));
try { Files.writeString(Path.of("no-such-log.txt"), "x\n", StandardOpenOption.APPEND); } catch (NoSuchFileException e) { System.out.println("APPEND alone needs an existing file: " + e.getMessage()); }
Files.delete(log); }}09:05 Asha IN 09:12 Ravi IN 13:00 Asha OUT APPEND alone needs an existing file: no-such-log.txt
What this code does
CREATEmakes the file on the first call;APPENDputs every later line after the existing text instead of replacing it.- As soon as you pass any option, the defaults are gone. With
APPENDalone there is noCREATE, so a missing file throwsNoSuchFileException.
The trap: once you pass any option, the defaults are switched off. APPEND alone needs the file to exist, so the usual pair is CREATE, APPEND: create it the first time, add to it after that.
CREATE_NEW to protect an existing file
StandardOpenOption.CREATE_NEW creates a new file and fails with FileAlreadyExistsException if the file already exists. The old file is never changed.
Example 5 · CREATE_NEW: never overwrite an existing receipt
import java.io.IOException;import java.nio.file.FileAlreadyExistsException;import java.nio.file.Files;import java.nio.file.Path;import java.nio.file.StandardOpenOption;
public class ReceiptDemo { static void saveReceipt(String number, String text) throws IOException { Path file = Path.of("receipt-" + number + ".txt"); try { Files.writeString(file, text, StandardOpenOption.CREATE_NEW); System.out.println("Saved " + file); } catch (FileAlreadyExistsException e) { System.out.println("Not saved, already exists: " + e.getMessage()); } }
public static void main(String[] args) throws IOException { saveReceipt("1001", "Hostel fee Rs 45000\n"); saveReceipt("1001", "Hostel fee Rs 18000\n");
Path saved = Path.of("receipt-1001.txt"); System.out.print("receipt-1001.txt: " + Files.readString(saved)); Files.delete(saved); }}Saved receipt-1001.txt Not saved, already exists: receipt-1001.txt receipt-1001.txt: Hostel fee Rs 45000
What this code does
- The second call uses the same receipt number by mistake.
CREATE_NEWrefuses withFileAlreadyExistsException, so the hostel fee receipt is safe. - The check and the create happen as one step inside the operating system, so two programs cannot both create the same receipt.
Use it when overwriting would destroy something real, such as a fee receipt or an exam result. The check and the create happen as a single step, which is safer than calling Files.exists first and writing after.
Rebuild the whole file each time → no options (the default). Add to a growing log → CREATE, APPEND. Create once and never overwrite → CREATE_NEW.
Next step
Check your understanding
11 quick questions