Skip to content

Commit 3a49faa

Browse files
committed
feat: serialize array of Customer objects to file
WHAT: - Added `WriteData` class to demonstrate serialization of multiple objects. - Created an array of `Customer` objects with unique IDs, names, and phone numbers. - Used `ObjectOutputStream` to serialize and persist the entire array into `Customer2.txt`. WHY: - To simplify serialization by writing an entire object array at once instead of looping over individual objects. - Demonstrates how Java’s serialization mechanism handles arrays of custom objects. KEY POINTS: - `Customer` implements `Serializable` so its objects can be persisted. - `static int count` ensures unique `custID` generation for each new customer. - `writeObject(list)` serializes the array and all contained objects in one step. - Output file is binary format, not human-readable, but can be deserialized back to objects. REAL-WORLD USE CASES: - Storing customer records in files before saving to a database. - Exporting application state or session data for later recovery. - Simple persistence mechanism for desktop or embedded applications. Signed-off-by: https://github.com/Someshdiwan <[email protected]>
1 parent 9b8b1e0 commit 3a49faa

File tree

2 files changed

+39
-0
lines changed

2 files changed

+39
-0
lines changed
Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
1+
import java.io.*;
2+
3+
class WriteCustomerData implements Serializable {
4+
String custID;
5+
String name;
6+
String phno;
7+
8+
static int count = 1;
9+
10+
void Customer(String n, String p) {
11+
custID = "C" + count; // Unique ID
12+
count++;
13+
name = n;
14+
phno = p;
15+
}
16+
17+
public String toString() {
18+
return "Customer ID: " + custID + "\nName: " + name + "\nPhno: " + phno + "\n";
19+
}
20+
}
21+
22+
public class WriteData {
23+
public static void main(String[] args) throws Exception {
24+
Customer list[] = {
25+
new Customer("Smith", "123456789"),
26+
new Customer("Johnson", "1234567"),
27+
new Customer("Ajay", "12345345")
28+
};
29+
30+
FileOutputStream fos = new FileOutputStream("/Users/somesh/Java SE/JavaEvolution-Learning-Growing-Mastering/Section23JavaIOStreams/src/MyJAVA/Customer2.txt");
31+
ObjectOutputStream oos = new ObjectOutputStream(fos);
32+
33+
oos.writeObject(list); // Serialize the entire array at once
34+
oos.close();
35+
fos.close();
36+
37+
System.out.println("Customer data serialized successfully.");
38+
}
39+
}
200 Bytes
Binary file not shown.

0 commit comments

Comments
 (0)