Today you will learn:
FileReader, BufferedReader, FileWriter, and BufferedWriterSerializable interfaceBy the end, you will be able to read and write files and serialize objects in Java.
Use BufferedWriter with FileWriter for efficient writing.
import java.io.*;
try(BufferedWriter writer = new BufferedWriter(new FileWriter("data.txt"))) {
writer.write("Hello Advanced Java!");
} catch(IOException e) {
e.printStackTrace();
}
Use BufferedReader with FileReader for efficient reading.
import java.io.*;
try(BufferedReader reader = new BufferedReader(new FileReader("data.txt"))) {
String line;
while((line = reader.readLine()) != null){
System.out.println(line);
}
} catch(IOException e) {
e.printStackTrace();
}
Serialization allows you to save objects to a file and read them back.
import java.io.*;
class Person implements Serializable {
private String name;
private int age;
public Person(String name, int age){
this.name = name;
this.age = age;
}
public String toString() {
return name + " is " + age + " years old.";
}
}
public class SerializeExample {
public static void main(String[] args) {
Person person = new Person("Alice", 25);
// Serialize
try(ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("person.dat"))) {
oos.writeObject(person);
} catch(IOException e) {
e.printStackTrace();
}
// Deserialize
try(ObjectInputStream ois = new ObjectInputStream(new FileInputStream("person.dat"))) {
Person readPerson = (Person) ois.readObject();
System.out.println(readPerson);
} catch(IOException | ClassNotFoundException e) {
e.printStackTrace();
}
}
}
import java.io.*;
try(BufferedWriter writer = new BufferedWriter(new FileWriter("data.txt"))) {
writer.write("Hello Advanced Java!");
}
try(BufferedReader reader = new BufferedReader(new FileReader("data.txt"))) {
String line;
while((line = reader.readLine()) != null){
System.out.println(line);
}
}
Serialize an object to a file and read it back.
Steps:
SerializableObjectOutputStreamObjectInputStreamExample:
import java.io.*;
class Student implements Serializable {
private String name;
private int id;
public Student(String name, int id){
this.name = name;
this.id = id;
}
public String toString() {
return "Student: " + name + ", ID: " + id;
}
}
public class StudentSerialize {
public static void main(String[] args) {
Student s = new Student("Bob", 101);
// Serialize
try(ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("student.dat"))) {
oos.writeObject(s);
} catch(IOException e) {
e.printStackTrace();
}
// Deserialize
try(ObjectInputStream ois = new ObjectInputStream(new FileInputStream("student.dat"))) {
Student readStudent = (Student) ois.readObject();
System.out.println(readStudent);
} catch(IOException | ClassNotFoundException e) {
e.printStackTrace();
}
}
}