Read and write files with the modern java.nio API, append text, check existence, and read input from the console.
Why: the modern way to touch files is the java.nio.file API — Path names a location and Files does the work. Files.writeString creates (or overwrites) a file with the given text in one call.
import java.nio.file.Files;
import java.nio.file.Path;
Path file = Path.of("notes.txt");
Files.writeString(file, "First line\nSecond line\n");
System.out.println("written to " + file.toAbsolutePath());Why: for a small file, readString pulls the entire contents into one String, and readAllLines gives you a List with one entry per line. Both throw IOException, so call them where that is handled.
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.List;
Path file = Path.of("notes.txt");
String all = Files.readString(file);
System.out.println(all);
List<String> lines = Files.readAllLines(file);
System.out.println("line count: " + lines.size());Why: by default writing replaces the whole file. Pass StandardOpenOption.APPEND to add to the end instead — useful for logs or growing records.
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.StandardOpenOption;
Path log = Path.of("app.log");
Files.writeString(log, "event happened\n", StandardOpenOption.CREATE,
StandardOpenOption.APPEND);Why: before reading you often want to know a file exists; Files gives quick yes/no checks and size. Path.of joins path pieces correctly for the operating system you are on.
import java.nio.file.Files;
import java.nio.file.Path;
Path file = Path.of("data", "notes.txt"); // data/notes.txt or data\notes.txt
System.out.println(Files.exists(file));
System.out.println(Files.isDirectory(Path.of("data")));Why: a Scanner reads what the user types at the terminal. Wrap System.in, then call nextLine() for text or nextInt() for a number. This is how a small command-line program asks questions.
import java.util.Scanner;
Scanner scanner = new Scanner(System.in);
System.out.print("What is your name? ");
String name = scanner.nextLine();
System.out.println("Hello, " + name + "!");
scanner.close();