File I/O with NIO
Demonstrates reading and writing files using Java NIO with Path, Files, and BufferedReader, including proper resource management and exception handling.
Code
import java.io.IOException;
import java.nio.file.*;
import java.util.List;
import java.util.stream.Stream;
public class FileReadWrite {
public static void main(String[] args) throws IOException {
Path dir = Path.of("output");
Path file = dir.resolve("data.txt");
Files.createDirectories(dir);
List<String> lines = List.of(
"First line",
"Second line",
"Third line"
);
Files.write(file, lines, StandardOpenOption.CREATE,
StandardOpenOption.TRUNCATE_EXISTING);
System.out.println("File size: " + Files.size(file) + " bytes");
try (Stream<String> fileLines = Files.lines(file)) {
fileLines.map(String::toUpperCase)
.forEach(System.out::println);
}
String content = Files.readString(file);
System.out.println("Total chars: " + content.length());
Files.deleteIfExists(file);
System.out.println("File deleted: " + !Files.exists(file));
}
}What the code does
The working surface is the class FileReadWrite — everything else is wiring.
try-with-resources closes each declared resource automatically on every exit path.
Applying it
Running the file prints labeled results such as File size:, Total chars:, File deleted: — each operation’s effect is visible in the output.
Statements that matter
fileLines.map(String::toUpperCase)
.forEach(System.out::println);
Interactive Tools for This Topic
Dotenv File ParserParse .env file content into a JSON object, handling comments, export prefixes, single quotes, and double-quoted escape sequences.INI File ParserParse INI configuration files into nested JSON with section objects, global keys, and both semicolon and hash comment support.JSON to TOML ConverterTurn a JSON object into TOML, emitting nested objects as tables and arrays of objects as array-of-tables blocks.JSON to YAML ConverterConvert JSON to readable YAML with nested block mappings, sequences, and quoting only where it is required.
FAQ
- What does File I/O with NIO print when run?
- Running the file directly is enough — expect labeled output lines such as `File size:`, `Total chars:`, `File deleted:`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.