This project focuses on the retrieval aspect of file management. It demonstrates how to use the java.nio.file package to read the contents of an existing text file. This is a critical skill for any application that needs to load settings, user data, or saved logs.
- Task: Read the entire content of
note.txt. - Method: Use
Files.readString(Path)for efficient reading. - Verification: Output the retrieved string to the console.
- Goal: Master basic file input operations using Java NIO.
- Java 8+ (NIO.2)
The application assumes the file note.txt exists in the root directory.
Paths.get("note.txt")creates a reference to the file location.Files.readString(path)reads all characters from the file into a singleString.- Error handling is implemented via a
try-catchblock to manageIOException, such as if the file is missing.
Reading from diary...
Content: Today is a great day!
Project Structure:
├── note.txt
└── src src/com/yurii/pavlenko/
└── Solution.java
Code
package com.yurii.pavlenko;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
public class Solution {
public static void main(String[] args) {
Path notePath = Paths.get("note.txt");
try {
System.out.println("Reading from diary...");
String content = Files.readString(notePath);
System.out.println("Content: " + content);
} catch (IOException e) {
System.out.println("Error: Could not read the file. " + e.getMessage());
}
}
}This project is licensed under the MIT License.
Copyright (c) 2026 Yurii Pavlenko
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files...
License: MIT