Java provides the java.io and java.nio packages to work with files. The most commonly used class is File, which allows you to create, read, write, and delete files.
Understanding the File Class
The File class represents file and directory pathnames.
import java.io.File;
public class FileObjectDemo {
public static void main(String[] args) {
File file = new File("data.txt");
System.out.println("File exists? " + file.exists());
}
}
1. Create a File
import java.io.File;
import java.io.IOException;
public class CreateFileDemo {
public static void main(String[] args) {
try {
File file = new File("example.txt");
if (file.createNewFile()) {
System.out.println("File Created: " + file.getName());
} else {
System.out.println("File already exists.");
}
} catch (IOException e) {
System.out.println("Error: " + e.getMessage());
}
}
}
2. Write to a File
You can use FileWriter or BufferedWriter to write text into a file.
import java.io.FileWriter;
import java.io.IOException;
public class WriteFileDemo {
public static void main(String[] args) {
try {
FileWriter writer = new FileWriter("example.txt");
writer.write("Hello from VINAR TECH Java Tutorials!");
writer.close();
System.out.println("Successfully wrote to file.");
} catch (IOException e) {
System.out.println("Error: " + e.getMessage());
}
}
}
3. Append to a File
import java.io.FileWriter;
import java.io.IOException;
public class AppendFileDemo {
public static void main(String[] args) {
try {
FileWriter writer = new FileWriter("example.txt", true); // true = append mode
writer.write("\nAppending new content...");
writer.close();
System.out.println("Content appended.");
} catch (IOException e) {
System.out.println("Error: " + e.getMessage());
}
}
}
4. Read a File
The Scanner class is one of the easiest ways to read text line-by-line.
import java.io.File;
import java.util.Scanner;
public class ReadFileDemo {
public static void main(String[] args) {
try {
File file = new File("example.txt");
Scanner reader = new Scanner(file);
while (reader.hasNextLine()) {
System.out.println(reader.nextLine());
}
reader.close();
} catch (Exception e) {
System.out.println("Error: " + e.getMessage());
}
}
}
5. Delete a File
import java.io.File;
public class DeleteFileDemo {
public static void main(String[] args) {
File file = new File("example.txt");
if (file.delete()) {
System.out.println("File deleted: " + file.getName());
} else {
System.out.println("Unable to delete file.");
}
}
}
6. Writing Files Efficiently with BufferedWriter
While FileWriter works fine for small files, it is recommended to use BufferedWriter for better performance when writing large amounts of data. BufferedWriter reduces disk I/O operations by writing data in chunks.
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
public class BufferedWriterDemo {
public static void main(String[] args) {
try (BufferedWriter bw = new BufferedWriter(new FileWriter("buffered.txt"))) {
bw.write("Writing data using BufferedWriter");
bw.newLine();
bw.write("This is faster and more efficient");
} catch (IOException e) {
System.out.println(e.getMessage());
}
}
}In real applications like logging systems and reports, BufferedWriter is preferred.
7. File Properties and Metadata
The File class provides useful methods to access file metadata such as size, absolute path, permissions, and last modified time.
import java.io.File;
public class FileInfoDemo {
public static void main(String[] args) {
File file = new File("example.txt");
System.out.println("File Name: " + file.getName());
System.out.println("Absolute Path: " + file.getAbsolutePath());
System.out.println("File Size: " + file.length() + " bytes");
System.out.println("Readable: " + file.canRead());
System.out.println("Writable: " + file.canWrite());
}
}8. Working with Directories
Java allows you to create, delete, and list directories using the same File class.
import java.io.File;
public class DirectoryDemo {
public static void main(String[] args) {
File dir = new File("myFolder");
if (dir.mkdir()) {
System.out.println("Directory created");
} else {
System.out.println("Directory already exists");
}
}
}This is commonly used in applications that generate reports, uploads, or logs.
9. Try-with-Resources in File Handling
Try-with-resources automatically closes files and streams, preventing memory leaks. It is the recommended approach for modern Java applications.
import java.io.FileWriter;
import java.io.IOException;
public class TryWithResourcesFile {
public static void main(String[] args) {
try (FileWriter writer = new FileWriter("autoClose.txt")) {
writer.write("File closed automatically");
} catch (IOException e) {
System.out.println(e.getMessage());
}
}
}10. Real-World Applications of File Handling
- Saving user data in desktop applications
- Generating reports (PDF, CSV, logs)
- Reading configuration files
- Uploading and downloading files in web apps
- Storing logs for debugging and monitoring
Almost every backend and desktop application relies on file handling in some form.
11. Common Mistakes in Java File Handling
- Forgetting to close file streams
- Hardcoding file paths
- Ignoring exceptions
- Using FileWriter instead of BufferedWriter for large files
Following best practices prevents memory leaks and file corruption issues.
12. Frequently Asked Interview Questions
- Difference between File and Files class?
- What is buffering and why is it important?
- How does try-with-resources work?
- How to handle large file reading efficiently?