Why files?
Variables disappear when a program ends. To keep data (marks, orders, logs) you save it to a file and read it back later. Modern Java uses the java.nio.file package: Path names a file and Files does the work.
Paths
import java.nio.file.Path;
Path p = Path.of("data", "marks.txt"); // data/marks.txt (or data\marks.txt on Windows)
System.out.println(p.getFileName()); // marks.txt
System.out.println(p.toAbsolutePath());
A relative path is resolved from the folder the program runs in.
Writing and reading a whole file
import java.io.IOException;
import java.nio.file.*;
import java.util.List;
public class Notes {
public static void main(String[] args) throws IOException {
Path file = Path.of("notes.txt");
Files.writeString(file, "Java\nPython\n"); // create or replace
Files.writeString(file, "Flutter\n", StandardOpenOption.APPEND); // add to the end
String all = Files.readString(file); // whole file as one String
List<String> lines = Files.readAllLines(file); // one String per line
System.out.println(lines); // [Java, Python, Flutter]
System.out.println(Files.exists(file)); // true
}
}
Files.write(path, listOfLines) writes a list, one item per line. Every file method can throw the checked IOException, so you must catch it or declare throws IOException.
Reading large files line by line
readAllLines loads everything into memory. For big files, read one line at a time:
import java.io.BufferedReader;
try (BufferedReader br = Files.newBufferedReader(Path.of("big-log.txt"))) {
String line;
int count = 0;
while ((line = br.readLine()) != null) {
if (line.contains("ERROR")) count++;
}
System.out.println(count + " errors");
} catch (IOException e) {
System.out.println("Cannot read: " + e.getMessage());
}
Files.lines(path) gives the lines as a stream: Files.lines(p).filter(l -> l.contains("ERROR")).count() (close it with try-with-resources too).
Writing with BufferedWriter
import java.io.BufferedWriter;
try (BufferedWriter bw = Files.newBufferedWriter(Path.of("report.txt"))) {
bw.write("Name,Marks");
bw.newLine();
bw.write("Asha,91");
bw.newLine();
}
The older classes FileReader, FileWriter and File still work and appear in many textbooks; Files and Path do the same jobs with less code.
Example: a CSV report
marks.csv:
Asha,91
Ravi,76
Meena,64
import java.io.IOException;
import java.nio.file.*;
public class CsvReport {
public static void main(String[] args) throws IOException {
int total = 0, n = 0;
for (String line : Files.readAllLines(Path.of("marks.csv"))) {
String[] parts = line.split(",");
String name = parts[0].trim();
int marks = Integer.parseInt(parts[1].trim());
System.out.printf("%-8s %3d%n", name, marks);
total += marks;
n++;
}
System.out.printf("Average: %.1f%n", (double) total / n);
}
}
Other file operations
Files.createDirectories(Path.of("backup/2026"));
Files.copy(Path.of("notes.txt"), Path.of("backup/2026/notes.txt"),
StandardCopyOption.REPLACE_EXISTING);
Files.move(Path.of("old.txt"), Path.of("new.txt"));
Files.deleteIfExists(Path.of("temp.txt"));
long bytes = Files.size(Path.of("notes.txt"));
The Date-Time API (java.time)
Java 8 added java.time, which replaces the old Date and Calendar classes. Its objects are immutable: methods return new objects.
| Class | Holds | Example |
|---|---|---|
LocalDate | a date | 2026-11-21 |
LocalTime | a time | 10:30 |
LocalDateTime | date and time | 2026-11-21T10:30 |
Period | a gap in years, months, days | 2 years 3 months |
Duration | a gap in hours, minutes, seconds | 90 minutes |
DateTimeFormatter | formatting and parsing | dd-MM-yyyy |
import java.time.*;
import java.time.format.DateTimeFormatter;
import java.time.temporal.ChronoUnit;
LocalDate today = LocalDate.now();
LocalDate exam = LocalDate.of(2026, 12, 15);
LocalDate due = today.plusDays(30);
System.out.println(exam.getDayOfWeek()); // TUESDAY
System.out.println(ChronoUnit.DAYS.between(today, exam)); // days left
System.out.println(exam.isAfter(today));
System.out.println(exam.isLeapYear()); // false
Age with Period
LocalDate dob = LocalDate.of(2009, 8, 15);
Period age = Period.between(dob, LocalDate.of(2026, 11, 21));
System.out.println(age.getYears() + " years " + age.getMonths() + " months"); // 17 years 3 months
Formatting and parsing
DateTimeFormatter f = DateTimeFormatter.ofPattern("dd-MM-yyyy");
String text = exam.format(f); // "15-12-2026"
LocalDate parsed = LocalDate.parse("26-01-2027", f);
DateTimeFormatter g = DateTimeFormatter.ofPattern("dd MMM yyyy, hh:mm a");
System.out.println(LocalDateTime.of(2026, 11, 21, 14, 5).format(g)); // 21 Nov 2026, 02:05 pm
In patterns, MM is month and mm is minutes; HH is 24-hour and hh 12-hour. (The AM/PM text depends on the computer's locale.)
Common mistakes
- Forgetting to handle
IOException: "unreported exception IOException; must be caught or declared to be thrown". - Reading a huge file with
readAllLinesand running out of memory. - Writing without
APPENDand replacing the file you meant to add to. - Not closing readers and writers; use try-with-resources.
- Using
mmfor months in a date pattern, or ignoring thatplusDaysreturns a new date.
Key points
Path.of(...)names a file;Filesreads, writes, copies, moves and deletes.Files.readString,readAllLines,writeStringandwritehandle small files in one line.- Use
BufferedReaderorFiles.linesfor large files, inside try-with-resources. LocalDate,LocalDateTime,PeriodandDateTimeFormatterhandle dates; they are immutable.
Practice questions
1. Append the line "Done" to log.txt, creating the file if it does not exist.
Files.writeString(Path.of("log.txt"), "Done\n",
StandardOpenOption.CREATE, StandardOpenOption.APPEND);2. Count the lines in data.txt.
long lines;
try (var s = Files.lines(Path.of("data.txt"))) {
lines = s.count();
}3. What is printed? LocalDate d = LocalDate.of(2026, 1, 31); d.plusMonths(1); System.out.println(d);
2026-01-31. plusMonths returns a new date, which was not stored.
4. Print today's date as, for example, 21/11/2026.
System.out.println(LocalDate.now().format(DateTimeFormatter.ofPattern("dd/MM/yyyy")));5. Why is IOException a checked exception?
Because file problems (missing files, no permission, a full disk) come from outside the program and can happen even in correct code, so Java makes the programmer plan for them.