Paths
Description
Path describes a location in the file system.
Explanation
Paths.get creates a Path from readable path segments.
Example
java.nio.file.Path path = java.nio.file.Paths.get("scores.txt");← Chapter 9 — Files & Regular Expressions
mixed
Java can read and write files using the java.nio.file package. Path represents a file location and Files provides concise operations for common tasks.
File operations can fail because a file is missing, unavailable, or unreadable. Use try-with-resources for streams and handle IOException appropriately.
Path describes a location in the file system.
Paths.get creates a Path from readable path segments.
java.nio.file.Path path = java.nio.file.Paths.get("scores.txt");Files has convenient static methods for text.
writeString and readString suit small text files.
java.nio.file.Files.writeString(path, "Aditi: 92");Use relative paths carefully: they are resolved from the program's working directory. Print path.toAbsolutePath while debugging if a file seems to be in the wrong place.
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
public class FileDemo {
public static void main(String[] args) throws IOException {
Path path = Path.of("student.txt");
Files.writeString(path, "Rohan: 88");
System.out.println(Files.readString(path));
}
}