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));
}
}Report a problem with this exampleOpens a pre-filled issue on GitHub.