Path and Files API In Java
In the Java programming language, NIO.2 introduced important Java features such as the Path and Files APIs in Java 7. These advanced concepts provide Java developers with a modern and easy way to work with custom files and directories stored in their storage systems.

To use them in a Java program, the Java developer must first implement or add the following Java package libraries to the top:
import java.nio.file.*;
Path API in Java.
In the Java file handling concept, Path indicates the storage location of a user-defined, created or stored file or directory in the system.
Creating a File Path in Java.
Path path = Paths.get(“samplefile.txt”);
To create a directory.
Path path = Paths.get(“C:/Users/Employee/Documents”);
Java users can also create their own path using this method.
Path path = Path.of(“samplefile.txt”);
In Java (The Path.of() function method was added in Java version 11.)
Essential Java file directory path methods.
getFileName() File or directory function.
The getFileName() function provides the name of a file or directory to a Java program.
Path path = Paths.get(“documents/samplefile.txt”);
System.out.println(path.getFileName());
Its output.
samplefile.txt
getParent() directory function.
The getParent() function provides the parent directory information to a Java program.
System.out.println(path.getParent());
Its output.
documents
getRoot() file function.
The getRoot() function provides detailed root information for a file path in a Java program.
Path path = Paths.get(“/home/employee/details.txt”);
System.out.println(path.getRoot());
Its output.
/
toAbsolutePath() file directory function.
The toAbsolutePath() function converts the path of a storage file to an absolute path in a Java program.
Path path = Paths.get(“samplefile.txt”);
System.out.println(path.toAbsolutePath());
Combining Java file paths.
The resolve() function is used to combine file paths in a Java program.
Path directory = Paths.get(“documents”);
Path file = directory.resolve(“samplefile.txt”);
System.out.println(file);
Its output.
documents/samplefile.txt
Comparing file paths in Java.
equals() file function.
equals() function in Java file program checks whether two existing file paths are equal or not.
Example of equals() file function.
import java.nio.file.Path;
import java.nio.file.Paths;
public class PathExplanation {
public static void main(String[] args) {
// here we used equals() function method to compare both file
Path f1 = Paths.get(“samplefile.txt”);
Path f2 = Paths.get(“samplefile.txt”);
System.out.println(“equals(): ” + f1.equals(f2));
// here we are creating a file path
Path path = Paths.get(“documents/samplefile.txt”);
// Here we used the startsWith() function method
System.out.println(“startsWith(): ” +
path.startsWith(“documents”));
// Here we used the endsWith() function method
System.out.println(“endsWith(): ” +
path.endsWith(“samplefile.txt”));
}
}
It’s output.
equals(): true
startsWith(): true
endsWith(): true
Files API concept in Java is a file directory.
The Files class in Java file directory management provides static methods for applying operations to files and directories.
Top Files API concept element.
- Files.createFile(…) – Used to create a file.
- Files.createDirectory(…) – Used to create a file directory.
- Files.delete(…) – Used to delete a file directory.
- Files.copy(…) – Used to copy.
- Files.move(…) – Used to move.
- Files.exists(…) – Used to check whether an object exists or not.
- Files.readAllLines(…) – Used to read all lines of a file.
- Files.write(…) – Used to write file information.
Checking whether a file exists in a Java file.
Path path = Paths.get(“samplefile.txt”);
if (Files.exists(path)) {
System.out.println(“Search File exists”);
}
Creating a file in Java.
Path path = Paths.get(“samplefile.txt”);
Files.createFile(path);
If the file already exists in the system, it throws an exception.
Creating a directory in Java.
Path path = Paths.get(“documents”);
Files.createDirectory(path);
Method for creating multiple Java directories.
Path path =
Paths.get(“data/java/files”);
Files.createDirectories(path);
Writing to a file in Java.
Example of Writing to a file in Java.
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.Files;
import java.io.IOException;
public class FileWriteIllustration {
public static void main(String[] args) {
try {
//here we are creating a file path
Path path = Paths.get(“samplefile.txt”);
//here we writing data into the file
Files.write(
path,
“this is a sample line”.getBytes()
);
System.out.println(“File Data written task successfully done”);
} catch (IOException ex) {
System.out.println(“Display Error -: ” + ex.getMessage());
}
}
}
Its output.
File Data written task successfully done
Java users can also write a list of lines in the created file.
List<String> lines =
Example of Writing to a list of lines file in Java.
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.Files;
import java.util.List;
import java.util.Arrays;
import java.io.IOException;
public class WriteMultipleText {
public static void main(String[] args) {
try {
//here we are creating file path
Path path = Paths.get(“samplefile.txt”);
// here we are creating a list of strings
List<String> text = Arrays.asList(
“sample java file”,
“sample java file text”,
“complete sample java file data”
);
// Here we are writing multiple lines into the samplefile.txt file
Files.write(path, text);
System.out.println(“Number of file text lines written successfully by me”);
} catch (IOException ex) {
System.out.println(“Display Error -: ” + ex.getMessage());
}
}
}
It’s output.
Number of file text lines written successfully by me
Reading a file in Java.
The readAllLines() function is used to read all file lines in a Java program.
Path path = Paths.get(“samplefile.txt”);
List<String> lines =
Files.readAllLines(path);
for (String line : lines) {
System.out.println(line);
}
For very large Java program files, streaming lines is often preferable.
Example of reading a file in Java.
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.Files;
import java.util.List;
import java.util.stream.Stream;
import java.io.IOException;
public class FileReadIllustration {
public static void main(String[] args) {
Path path = Paths.get(“samplefile.txt”);
try {
// Method 1: here we using readAllLines() function for all file line reading
System.out.println(“Here we use readAllLines() method.”);
List<String> lines =
Files.readAllLines(path);
for (String line : lines) {
System.out.println(line);
}
// Method 2: here we using Files.lines() method
System.out.println(“\n We use Files.lines() method.”);
try (Stream<String> fileLines =
Files.lines(path)) {
fileLines.forEach(System.out::println);
}
} catch (IOException ex) {
System.out.println(“Display Error -: ” + ex.getMessage());
}
}
}
Its output.
Here we use readAllLines() method.
Display Error -: samplefile.txt
Copying a file in a Java program.
Java users can copy file elements using the copy method.
Path source =
Example of Copying a file in a Java program.
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.Files;
import java.nio.file.StandardCopyOption;
import java.io.IOException;
public class FileCopyIllustration {
public static void main(String[] args) {
try {
// here is the source file
Path source = Paths.get(“samplefile.txt”);
// here is the destination file
Path destination = Paths.get(“filebackup.txt”);
// here is the copying of the file
Files.copy(source, destination);
System.out.println(“File copied process successfully done”);
// here is the replacing an existing destination file
Files.copy(
source,
destination,
StandardCopyOption.REPLACE_EXISTING
);
System.out.println(“Your desire Existing file replaced task successfully done”);
} catch (IOException ex) {
System.out.println(“Display Error -: ” + ex.getMessage());
}
}
}
Its output.
Your desire Existing file replaced task successfully done
Moving a File in a Java Program.
Path source =
Example of Moving a File in a Java Program.
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.Files;
import java.io.IOException;
public class FileMoveIllustration {
public static void main(String[] args) {
try {
// here is the source file
Path source = Paths.get(“samplefile.txt”);
// here is the destination file path
Path destination =
Paths.get(“documents/samplefile.txt”);
// here we moving the file
Files.move(source, destination);
System.out.println(“File moved operation successfully done”);
} catch (IOException ex) {
System.out.println(“Display Error -: ” + ex.getMessage());
}
}
}
Its output.
File moved operation successfully done
Deleting a file in a Java program.
Example of a file in a Java program.
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.Files;
import java.io.IOException;
public class FileDeleteIllustration {
public static void main(String[] args) {
try {
//here we are creating file path
Path path = Paths.get(“samplefile.txt”);
// Method 1: here we used it for Delete a file
Files.delete(path);
System.out.println(“Your desire File deleted task successfully done”);
// Method 2: Here we delete a file only if it exists in the system.
boolean output = Files.deleteIfExists(path);
if (output) {
System.out.println(“File deletion task successfully completed”);
} else {
System.out.println(“Your file does not exist in the system”);
}
} catch (IOException ex) {
System.out.println(“Display Error -: ” + ex.getMessage());
}
}
}
It’s output.
Your desired file deletion task successfully completed.
Your file does not exist in the system.
Checking a File’s Properties in Java.
Java users can check whether a file path is a file or a directory location in an existing program.
Path path = Paths.get(“samplefile.txt”);
System.out.println(Files.isRegularFile(path));
System.out.println(Files.isDirectory(path));
Java users can also use this in other ways.
Files.isReadable(path);
Files.isWritable(path);
Files.isExecutable(path);
Listing directory contents in Java.
The Files.list() function method in a Java program provides a stream of paths to the Java user.
Path directory =
Paths.get(“documents”);
try (Stream<Path> files =
Files.list(directory)) {
files.forEach(System.out::println);
}
This lists the contents of the directory immediately in the current program.
Walking through the Java directory tree.
The Files.walk() function in a Java program can traverse a directory and its subdirectories.
Path directory =
Paths.get(“documents”);
try (Stream<Path> paths =
Files.walk(directory)) {
paths.forEach(System.out::println);
}
This Java function is used when a Java user needs to process files repeatedly.
Detail Compassion Between Directory Path Vs Files Path Location
| # | Directory Path Concept | Files Path Concept |
| 1. | It Represents a file/directory storage location | it helps java use to performs operations on files/directories path |
| 2. | It Represents a specific unique directory path | It Provides us static utility file path methods |
| 3. | We use it with Paths.get() / Path.of() directory function | We use it with Files.createFile() function or method to create file |
| 4. | We used getFileName() function for directory | In this we used Files.readAllLines() for reading all file lines |
| 5. | We used getParent() function to get parent directory detail | Here we used Files.write() function to write data and info into file |
| 6. | We used resolve() function to group directory and file path | Here we used Files.copy() method to copy file element or data |
| 7. | We used toAbsolutePath() function to get absolute directory path | Here we used Files.delete() function to delete unwanted system file |
An easy way to remember the path to a file directory in Java.
File Directory Path
↓
Where is the file’s storage location?
Java Files
↓
Can a Java user apply desired file operations?
Complete Java File Example.
import java.nio.file.*;
import java.util.*;
public class Main {
public static void main(String[] args)
throws Exception {
//here we are creating file path
Path path = Paths.get(“samplefile.txt”);
// 1. here we write data into the file
Files.write(
path,
Arrays.asList(“Data”, “Html”, “Sample info” , “Welcome to java file concept”)
);
System.out.println(“User define custom file data task written successfully done”);
// 2. here we check if the file exists or not
System.out.println(“File exists: ” +
Files.exists(path));
// 3. here we read all lines from the file
List<String> lines =
Files.readAllLines(path);
// 4. here we display file contents
System.out.println(“The actual file data contents is-:”);
lines.forEach(System.out::println);
}
}
Its output.
User define custom file data task written successfully done
File exists: true
The actual file contents is-:
data
Html
Sample info
Welcome to java file concept
Conclusion of Path and Files API In Java.
- In a Java file directory program, Path indicates the storage location of a file or directory.
- In the Java Files program, multiple function methods are provided for creating files, reading files, writing files, copying files, moving files, deleting file data files, and inspecting them later.
- In Java, the Files.list() function method is used to list directory contents.
- The Files.walk() function method is used to traverse a directory tree.
- In a Java file directory, Path and Files are important elements of Java NIO.2.

