File handling in Java allows programs to store data permanently, read data from files, and manipulate file systems. Java provides rich support for file operations through the java.io and java.nio packages. File handling is essential for applications such as logging systems, data storage, report generation, configuration management, and serialization.
The File class (from java.io package) is used to represent a file or directory path.
It does not read or write data — it only provides metadata and file operations.
import java.io.File;
public class FileDemo {
public static void main(String[] args) {
File file = new File("sample.txt");
System.out.println("Exists: " + file.exists());
System.out.println("File name: " + file.getName());
System.out.println("Absolute path: " + file.getAbsolutePath());
}
}
Java provides two types of streams for file handling.
FileInputStream, FileOutputStreamimport java.io.FileOutputStream;
public class ByteWrite {
public static void main(String[] args) throws Exception {
FileOutputStream fos = new FileOutputStream("data.bin");
fos.write(65); // writes 'A'
fos.close();
}
}
FileReader, FileWriterimport java.io.FileReader;
public class CharRead {
public static void main(String[] args) throws Exception {
FileReader fr = new FileReader("sample.txt");
int ch;
while ((ch = fr.read()) != -1) {
System.out.print((char) ch);
}
fr.close();
}
}
| Byte Stream | Character Stream |
|---|---|
| Binary data | Text data |
| Faster for media | Handles Unicode |
| FileInputStream | FileReader |
Buffered streams improve performance by reading or writing data in chunks instead of one character at a time.
import java.io.*;
public class BufferedRead {
public static void main(String[] args) throws Exception {
BufferedReader br = new BufferedReader(new FileReader("sample.txt"));
String line;
while ((line = br.readLine()) != null) {
System.out.println(line);
}
br.close();
}
}
newLine() methodimport java.io.*;
public class BufferedWrite {
public static void main(String[] args) throws Exception {
BufferedWriter bw = new BufferedWriter(new FileWriter("sample.txt"));
bw.write("Welcome to Java File Handling");
bw.newLine();
bw.write("Buffered Writer Example");
bw.close();
}
}
FileWriterBufferedWriterFileOutputStreamFileReaderBufferedReaderFileInputStreamimport java.io.*;
public class ReadWriteDemo {
public static void main(String[] args) throws Exception {
FileWriter fw = new FileWriter("info.txt");
fw.write("Java File Handling");
fw.close();
FileReader fr = new FileReader("info.txt");
int ch;
while ((ch = fr.read()) != -1) {
System.out.print((char) ch);
}
fr.close();
}
}
Serialization is the process of converting an object into a byte stream so that it can be stored in a file or sent over a network.
Serializabletransient are not serializedimport java.io.*;
class Student implements Serializable {
int id;
String name;
Student(int id, String name) {
this.id = id;
this.name = name;
}
}
public class SerializeDemo {
public static void main(String[] args) throws Exception {
Student s = new Student(1, "Prakash");
ObjectOutputStream oos =
new ObjectOutputStream(new FileOutputStream("student.ser"));
oos.writeObject(s);
oos.close();
}
}
import java.io.*;
public class DeserializeDemo {
public static void main(String[] args) throws Exception {
ObjectInputStream ois =
new ObjectInputStream(new FileInputStream("student.ser"));
Student s = (Student) ois.readObject();
System.out.println(s.id + " " + s.name);
ois.close();
}
}
File file = new File("newfile.txt");
file.createNewFile();
file.delete();
File oldFile = new File("old.txt");
File newFile = new File("new.txt");
oldFile.renameTo(newFile);
File dir = new File("MyFolder");
dir.mkdir();
java
import java.io.*;
// Serializable class
class Employee implements Serializable {
private static final long serialVersionUID = 1L;
private String name;
private int id;
private transient String password; // Won't be serialized
public Employee(String name, int id, String password) {
this.name = name;
this.id = id;
this.password = password;
}
@Override
public String toString() {
return "Employee{name='" + name + "', id=" + id + "}";
}
}
public class FileIODemo {
public static void main(String[] args) {
// Writing to a file
try (BufferedWriter writer = new BufferedWriter(new FileWriter("output.txt"))) {
writer.write("Hello, File I/O!");
writer.newLine();
writer.write("This is line 2");
System.out.println("File written successfully");
} catch (IOException e) {
e.printStackTrace();
}
// Reading from a file
try (BufferedReader reader = new BufferedReader(new FileReader("output.txt"))) {
String line;
while ((line = reader.readLine()) != null) {
System.out.println(line);
}
} catch (IOException e) {
e.printStackTrace();
}
// Serialization
Employee emp = new Employee("John Doe", 101, "secret123");
try (ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("employee.ser"))) {
oos.writeObject(emp);
System.out.println("Object serialized");
} catch (IOException e) {
e.printStackTrace();
}
// Deserialization
try (ObjectInputStream ois = new ObjectInputStream(new FileInputStream("employee.ser"))) {
Employee deserializedEmp = (Employee) ois.readObject();
System.out.println("Deserialized: " + deserializedEmp);
} catch (IOException | ClassNotFoundException e) {
e.printStackTrace();
}
// File operations
File file = new File("test.txt");
try {
if (file.createNewFile()) {
System.out.println("File created: " + file.getName());
}
System.out.println("File exists: " + file.exists());
System.out.println("Absolute path: " + file.getAbsolutePath());
System.out.println("File size: " + file.length() + " bytes");
} catch (IOException e) {
e.printStackTrace();
}
}
}