File Handling in Java - Detailed Explanation
1. What is File Handling?
File handling allows you to create, read, update, and delete files from your Java program. Java provides two major APIs:
java.io (traditional) and java.nio.file (modern, powerful, introduced in Java 7).
2. The File Class (java.io.File)
This class is used to represent file and directory pathnames. It is used for metadata and directory operations.
Example:
import java.io.File;
import java.io.IOException;
public class FileClassExample {
public static void main(String[] args) {
File file = new File("demo.txt");
try {
if (file.createNewFile()) {
System.out.println("File created: " + file.getName());
} else {
System.out.println("File already exists.");
}
System.out.println("Absolute path: " + file.getAbsolutePath());
} catch (IOException e) {
e.printStackTrace();
}
}
}
3. Reading from a File
a) Using FileReader and BufferedReader:
import java.io.*;
public class ReadTextFile {
public static void main(String[] args) {
try {
BufferedReader br = new BufferedReader(new FileReader("demo.txt"));
String line;
while ((line = br.readLine()) != null) {
System.out.println(line);
}
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
b) Using FileInputStream:
import java.io.*;
public class ReadBinaryFile {
public static void main(String[] args) {
try {
FileInputStream fis = new FileInputStream("image.png");
int data;
while ((data = fis.read()) != -1) {
System.out.print((char) data);
}
fis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
4. Writing to a File
a) Using FileWriter and BufferedWriter:
import java.io.*;
public class WriteToFile {
public static void main(String[] args) {
try {
BufferedWriter bw = new BufferedWriter(new FileWriter("demo.txt"));
bw.write("Hello Java!");
bw.newLine();
bw.write("File handling is powerful.");
bw.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
b) Using FileOutputStream:
import java.io.*;
public class WriteBinaryFile {
public static void main(String[] args) {
try {
FileOutputStream fos = new FileOutputStream("output.bin");
String content = "Hello in bytes!";
fos.write(content.getBytes());
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
5. Appending to a File
import java.io.*;
public class AppendToFile {
public static void main(String[] args) {
try {
BufferedWriter bw = new BufferedWriter(new FileWriter("demo.txt", true));
bw.write("Appended line.");
bw.newLine();
bw.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
6. File Deletion
import java.io.File;
public class DeleteFile {
public static void main(String[] args) {
File file = new File("demo.txt");
if (file.delete()) {
System.out.println("Deleted successfully.");
} else {
System.out.println("Failed to delete file.");
}
}
}
7. Modern File Handling using java.nio.file
import java.nio.file.*;
import java.io.IOException;
public class NIOFileExample {
public static void main(String[] args) {
Path path = Paths.get("nio_example.txt");
try {
Files.write(path, "Hello NIO!".getBytes());
String content = new String(Files.readAllBytes(path));
System.out.println(content);
} catch (IOException e) {
e.printStackTrace();
}
}
}
8. Reading All Lines at Once
import java.nio.file.*;
import java.io.IOException;
import java.util.List;
public class ReadAllLines {
public static void main(String[] args) throws IOException {
List<String> lines = Files.readAllLines(Paths.get("demo.txt"));
for (String line : lines) {
System.out.println(line);
}
}
}
9. Try-with-Resources
import java.io.*;
public class SafeRead {
public static void main(String[] args) {
try (BufferedReader br = new BufferedReader(new FileReader("demo.txt"))) {
String line;
while ((line = br.readLine()) != null)
System.out.println(line);
} catch (IOException e) {
e.printStackTrace();
}
}
}
10. Common Exceptions
- FileNotFoundException: File not found when trying to read.
- IOException: General input/output error.
- SecurityException: Access to file denied.
- NullPointerException: File object is null.