🎓 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 (178K+ subscribers): Java Guides on YouTube
▶️ For AI, ChatGPT, Web, Tech, and Generative AI, subscribe to another channel: Ramesh Fadatare on YouTube
Introduction
File operations such as creating, reading, writing, and deleting files are common tasks in many Java applications. Java provides several classes and methods to perform these operations efficiently. This guide will demonstrate how to create, read, write, and delete files using both the java.io and java.nio.file packages.
Table of Contents
- Importing Required Packages
- Creating a File
- Writing to a File
- Reading from a File
- Deleting a File
- Complete Example
- Conclusion
Importing Required Packages
To perform file operations, you need to import the necessary classes from the java.io and java.nio.file packages.
Example
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;
import java.util.List;
import java.util.Arrays;
Creating a File
To create a file, you can use either the File class or the Files.createFile() method from the java.nio.file package.
Example
Using File Class
import java.io.File;
import java.io.IOException;
public class CreateFileExample {
public static void main(String[] args) {
File file = new File("example.txt");
try {
if (file.createNewFile()) {
System.out.println("File created successfully: " + file.getAbsolutePath());
} else {
System.out.println("File already exists.");
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
Using Files.createFile() Method
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.io.IOException;
public class CreateFileNIOExample {
public static void main(String[] args) {
Path filePath = Paths.get("example.txt");
try {
Files.createFile(filePath);
System.out.println("File created successfully: " + filePath.toAbsolutePath());
} catch (IOException e) {
e.printStackTrace();
}
}
}
Writing to a File
To write to a file, you can use either the FileWriter and BufferedWriter classes or the Files.write() method from the java.nio.file package.
Example
Using FileWriter and BufferedWriter Classes
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
public class WriteFileExample {
public static void main(String[] args) {
try (BufferedWriter writer = new BufferedWriter(new FileWriter("example.txt", true))) {
writer.write("First line\n");
writer.write("Second line\n");
writer.write("Third line\n");
System.out.println("Data written to file successfully.");
} catch (IOException e) {
e.printStackTrace();
}
}
}
Using Files.write() Method
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;
import java.io.IOException;
import java.util.List;
import java.util.Arrays;
public class WriteFileNIOExample {
public static void main(String[] args) {
Path filePath = Paths.get("example.txt");
List<String> lines = Arrays.asList("First line", "Second line", "Third line");
try {
Files.write(filePath, lines, StandardOpenOption.CREATE, StandardOpenOption.APPEND);
System.out.println("Data written to file successfully.");
} catch (IOException e) {
e.printStackTrace();
}
}
}
Reading from a File
To read from a file, you can use either the FileReader and BufferedReader classes or the Files.readAllLines() method from the java.nio.file package.
Example
Using FileReader and BufferedReader Classes
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
public class ReadFileExample {
public static void main(String[] args) {
try (BufferedReader reader = new BufferedReader(new FileReader("example.txt"))) {
String line;
while ((line = reader.readLine()) != null) {
System.out.println(line);
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
Using Files.readAllLines() Method
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.io.IOException;
import java.util.List;
public class ReadFileNIOExample {
public static void main(String[] args) {
Path filePath = Paths.get("example.txt");
try {
List<String> lines = Files.readAllLines(filePath);
for (String line : lines) {
System.out.println(line);
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
Deleting a File
To delete a file, you can use either the File.delete() method or the Files.deleteIfExists() method from the java.nio.file package.
Example
Using File.delete() Method
import java.io.File;
public class DeleteFileExample {
public static void main(String[] args) {
File file = new File("example.txt");
if (file.delete()) {
System.out.println("File deleted successfully: " + file.getAbsolutePath());
} else {
System.out.println("Failed to delete the file.");
}
}
}
Using Files.deleteIfExists() Method
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.io.IOException;
public class DeleteFileNIOExample {
public static void main(String[] args) {
Path filePath = Paths.get("example.txt");
try {
if (Files.deleteIfExists(filePath)) {
System.out.println("File deleted successfully: " + filePath.toAbsolutePath());
} else {
System.out.println("File does not exist.");
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
Complete Example
Here is a complete example demonstrating how to create, write, read, and delete a file using both the java.io and java.nio.file packages with proper exception handling.
FileOperationsExample.java
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;
import java.util.List;
import java.util.Arrays;
public class FileOperationsExample {
public static void main(String[] args) {
// Create a file using File class
File file = new File("example.txt");
try {
if (file.createNewFile()) {
System.out.println("File created successfully: " + file.getAbsolutePath());
} else {
System.out.println("File already exists.");
}
} catch (IOException e) {
e.printStackTrace();
}
// Write to the file using BufferedWriter
try (BufferedWriter writer = new BufferedWriter(new FileWriter("example.txt", true))) {
writer.write("First line\n");
writer.write("Second line\n");
writer.write("Third line\n");
System.out.println("Data written to file successfully.");
} catch (IOException e) {
e.printStackTrace();
}
// Read from the file using BufferedReader
try (BufferedReader reader = new BufferedReader(new FileReader("example.txt"))) {
String line;
while ((line = reader.readLine()) != null) {
System.out.println(line);
}
} catch (IOException e) {
e.printStackTrace();
}
// Delete the file using File class
if (file.delete()) {
System.out.println("File deleted successfully: " + file.getAbsolutePath());
} else {
System.out.println("Failed to delete the file.");
}
// Create a file using Files.createFile() method
Path filePath = Paths.get("example.txt");
try {
Files.createFile(filePath);
System.out.println("File created successfully: " + filePath.toAbsolutePath());
} catch (IOException e) {
e.printStackTrace();
}
// Write to the file using Files.write() method
List<String> lines = Arrays.asList("First line", "Second line", "Third line");
try {
Files.write(filePath, lines, StandardOpenOption.CREATE, StandardOpenOption.APPEND);
System.out.println("Data written to file successfully.");
} catch (IOException e) {
e.printStackTrace();
}
// Read from the file using Files.readAllLines() method
try {
List<String> readLines = Files.readAllLines(filePath);
for (String line : readLines) {
System.out.println(line);
}
} catch (IOException e) {
e.printStackTrace();
}
// Delete the file using Files.deleteIfExists() method
try {
if (Files.deleteIfExists(filePath)) {
System.out.println("File deleted successfully: " + filePath.toAbsolutePath());
} else {
System.out.println("File does not exist.");
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
Conclusion
Java provides multiple ways to perform file operations such as creating, reading, writing, and deleting files. By using the java.io and java.nio.file packages, you can efficiently manage file operations in your Java applications. Understanding how to use these methods and handle potential exceptions ensures robust and error-free file handling in your programs.
My Top and Bestseller Udemy Courses. The sale is going on with a 70 - 80% discount. The discount coupon has been added to each course below:
Build REST APIs with Spring Boot 4, Spring Security 7, and JWT
[NEW] Learn Apache Maven with IntelliJ IDEA and Java 25
ChatGPT + Generative AI + Prompt Engineering for Beginners
Spring 7 and Spring Boot 4 for Beginners (Includes 8 Projects)
Available in Udemy for Business
Building Real-Time REST APIs with Spring Boot - Blog App
Available in Udemy for Business
Building Microservices with Spring Boot and Spring Cloud
Available in Udemy for Business
Java Full-Stack Developer Course with Spring Boot and React JS
Available in Udemy for Business
Build 5 Spring Boot Projects with Java: Line-by-Line Coding
Testing Spring Boot Application with JUnit and Mockito
Available in Udemy for Business
Spring Boot Thymeleaf Real-Time Web Application - Blog App
Available in Udemy for Business
Master Spring Data JPA with Hibernate
Available in Udemy for Business
Spring Boot + Apache Kafka Course - The Practical Guide
Available in Udemy for Business
Comments
Post a Comment
Leave Comment