📘 Premium Read: Access my best content on Medium member-only articles — deep dives into Java, Spring Boot, Microservices, backend architecture, interview preparation, career advice, and industry-standard best practices.
🎓 Top 15 Udemy Courses (80-90% Discount): My Udemy Courses - Ramesh Fadatare — All my Udemy courses are real-time and project oriented courses.
▶️ Subscribe to My YouTube Channel (176K+ subscribers): Java Guides on YouTube
▶️ For AI, ChatGPT, Web, Tech, and Generative AI, subscribe to another channel: Ramesh Fadatare on YouTube
The Java NIO Files class (java.nio.file.Files) provides several methods for manipulating files in the file system. This Java NIO Files guide will cover the most commonly used of these methods. The Files class contains many methods, so check the JavaDoc too, if you need a method that is not described here.
The java.nio.file.Files class works with java.nio.file.Path instances, so you need to understand the Path class before you can work with the Files class.
1. Files.createFile() API/Method
Java Files.createFile() Example
package net.javaguides.corejava.io;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
public class JavaCreateFile {
public static void main(String[] args) throws IOException {
Path myPath = Paths.get("src/myfile.txt");
if (Files.exists(myPath)) {
System.out.println("File already exists");
} else {
Files.createFile(myPath);
System.out.println("File created");
}
}
}
File created
2. Files.readAllLines() API/Method
Java Files.readAllLines() API Example
package net.javaguides.corejava.io;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.List;
public class JavaReadFile {
public static void main(String[] args) throws IOException {
Path myPath = Paths.get("src/net/javaguides/corejava/io/JavaReadFile.java");
List < String > lines = Files.readAllLines(myPath, StandardCharsets.UTF_8);
lines.forEach(line - > System.out.println(line));
}
}
package net.javaguides.corejava.io;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.List;
public class JavaReadFile {
public static void main(String[] args) throws IOException {
Path myPath = Paths.get("src/net/javaguides/corejava/io/JavaReadFile.java");
List<String> lines = Files.readAllLines(myPath, StandardCharsets.UTF_8);
lines.forEach(line -> System.out.println(line));
}
}
3. Files.write() API/Method
Java Files.write() API Example
package net.javaguides.corejava.io;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;
import java.util.ArrayList;
import java.util.List;
public class JavaWriteFile {
public static void main(String[] args) throws IOException {
Path myPath = Paths.get("src/resources/myfile.txt");
List < String > animals = new ArrayList < > ();
// Adding new elements to the ArrayList
animals.add("Lion");
animals.add("Tiger");
animals.add("Cat");
animals.add("Dog");
System.out.println(animals);
Files.write(myPath, animals, StandardCharsets.UTF_8,
StandardOpenOption.CREATE);
System.out.println("Data written");
}
}
Data written
4. Files.deleteIfExists(Path path) API/Method
Java Files.deleteIfExists() API Example
package net.javaguides.corejava.io;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
public class JavaDeleteFile {
public static void main(String[] args) throws IOException {
Path myPath = Paths.get("src/sample1.txt");
boolean fileDeleted = Files.deleteIfExists(myPath);
if (fileDeleted) {
System.out.println("File deleted");
} else {
System.out.println("File does not exist");
}
}
}
File deleted
5. Files.move() API/Method
Java Files.move() API Example
package net.javaguides.corejava.io;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
public class JavaMoveFile {
public static void main(String[] args) throws IOException {
Path myPath = Paths.get("src/myfile.txt");
Path myPath2 = Paths.get("src/myfile2.txt");
Files.move(myPath, myPath2);
System.out.println("File moved");
}
}
File moved
6. Files.copy() API/Method
This method copy a file to a target file.
This method copies a file to the target file with the options parameter specifying how the copy is performed. By default, the copy fails if the target file already exists or is a symbolic link, except if the source and target are the same file, in which case the method completes without copying the file.
Java Files.copy() API Example
Let's first create a file named "sample1.txt" and enter some text in it. Once you run below program, the content of "sample1.txt" file should be copied to "sample2.txt" file:
package net.javaguides.corejava.io;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.StandardCopyOption;
public class JavaCopyFile {
public static void main(String[] args) throws IOException {
File source = new File("src/sample1.txt");
File dest = new File("src/sample2.txt");
Files.copy(source.toPath(), dest.toPath(),
StandardCopyOption.REPLACE_EXISTING);
}
}
7. Files.getOwner() API/Method
Java Files.getOwner API Example
package net.javaguides.corejava.io;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.attribute.UserPrincipal;
public class JavaGetFileOwner {
public static void main(String[] args) throws IOException {
Path myPath = Paths.get("src/sample.txt");
UserPrincipal userPrincipal = Files.getOwner(myPath);
String owner = userPrincipal.getName();
System.out.println(owner);
}
}
Ramesh\CM-1787
8. Append to file with Files.write() API
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;
public class JavaAppendFileFiles {
public static void main(String[] args) throws IOException {
String fileName = "src/main/resources/sample.txt";
byte[] tb = "Ramesh \n".getBytes();
Files.write(Paths.get(fileName), tb, StandardOpenOption.APPEND);
}
}
9. Java creates a directory with Files.createDirectory() API/Method
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
public class JavaCreateDirectory {
public static void main(String[] args) throws IOException {
String fileName = "/home/ramesh/tmp/newdir";
Path path = Paths.get(fileName);
if (!Files.exists(path)) {
Files.createDirectory(path);
System.out.println("Directory created");
} else {
System.out.println("Directory already exists");
}
}
}
10. Java file size with Files.size() API/Method
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
public class JavaFileSizeExample {
public static void main(String[] args) throws IOException {
String fileName = "src/main/resources/words.txt";
Path filePath = Paths.get(fileName);
long fileSize = Files.size(filePath);
System.out.format("The size of the file: %d bytes", fileSize);
}
}
The size of the file: 200 bytes
Comments
Post a Comment
Leave Comment