Summary - I/O and NIO basics
- Java course
- Advanced
- Lesson 72/82
- 5 min
Combine Path, Files and readString to write a file scanner.
Summary - I/O and NIO basics
In this group you saw the core NIO.2 tools: paths with Path, file operations with Files, easy text with readString/writeString, buffered reading with BufferedReader, and NIO channels with FileChannel. These tools are the foundation of file handling in Java.
Now you will combine these into a mini task: building a small notebook structure.
Practice Notebook: write and read
Write main in a Notebook class; create a temp file with Files.createTempFile("n", ".txt"). Write with Files.writeString(p, "Note 1"). Read with String s = Files.readString(p). Print with System.out.println(s).
Starter code
import java.nio.file.*;
// Write main in Notebook
// Use createTempFile, writeString and readString to write and read a noteSample solution
import java.nio.file.*;
class Notebook {
public static void main(String[] args) throws Exception {
Path p = Files.createTempFile("n", ".txt");
Files.writeString(p, "Note 1");
String s = Files.readString(p);
System.out.println(s);
}
}Expected output
Note 1
Practice Read a line with BufferedReader
Write main in a new LineDemo class; create a temp file with Files.createTempFile("l", ".txt"), write Files.writeString(p, "Line 1"). In a try (BufferedReader r = Files.newBufferedReader(p)) block, call r.readLine() and print it.
Starter code
import java.nio.file.*;
import java.io.*;
// Write main in LineDemo
// Set up with createTempFile and writeString; call readLine in BufferedReader and printSample solution
import java.nio.file.*;
import java.io.*;
class LineDemo {
public static void main(String[] args) throws Exception {
Path p = Files.createTempFile("l", ".txt");
Files.writeString(p, "Line 1");
try (BufferedReader r = Files.newBufferedReader(p)) {
System.out.println(r.readLine());
}
}
}Expected output
Line 1
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 What is the best method to read a small text in one go?
- FileChannel
- Files.readString Correct answer
- InputStream.read
- BufferedReader.readLine
Explanation: Files.readString is ideal for small texts.
2 Match the I/O summary
| Term | Meaning |
|---|---|
Path |
Represents a path |
Files |
File operations |
readString |
Reads text |
FileChannel |
NIO channel |