Skip to content

Commit 2015cf0

Browse files
committed
feat: add DataOutputStream example for serializing Student object
WHAT: - Implemented `DataOutputStreamsExample` class. - Created `Student11` class with fields: rollno, name, avg, dept. - Used `DataOutputStream` with `FileOutputStream` to write student data into a file. HOW: 1. Instantiated a `Student11` object and populated sample data. 2. Opened `FileOutputStream` pointing to `Student1.txt`. 3. Wrapped it with `DataOutputStream` for writing Java primitives in binary. 4. Wrote fields in a specific order: - `writeInt()` → roll number - `writeUTF()` → name - `writeUTF()` → department - `writeFloat()` → average 5. Closed streams safely after writing. 6. Data is saved in **binary format**, not human-readable text. WHY: - Demonstrates **manual serialization** using `DataOutputStream`. - Ensures data is written in a **platform-independent binary format**. - Reading must follow the **exact same order** using `DataInputStream`. REAL-WORLD APPLICATIONS: - Saving student records or user profiles in lightweight storage. - Writing config/state data in binary (faster than plain text parsing). - Efficient persistence in games, finance apps, or IoT systems. - Forms the basis of custom serialization frameworks. BENEFITS: - Compact and efficient storage (binary instead of text). - Machine-independent format due to `DataOutputStream`. - Works with Java primitive types and UTF-encoded Strings. NEXT IMPROVEMENTS: - Add matching `DataInputStreamsExample` to read and reconstruct `Student11`. - Refactor into reusable `writeStudent(Student11 student, File file)` method. - Add try-with-resources for cleaner resource management. Signed-off-by: https://github.com/Someshdiwan <[email protected]>
1 parent 7949c9e commit 2015cf0

File tree

2 files changed

+2
-3
lines changed

2 files changed

+2
-3
lines changed

Section23JavaIOStreams/Serialisation Storing Data in a File/src/DataOutputStreamsExample.java

Lines changed: 2 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -2,8 +2,7 @@
22
import java.io.*;
33
import java.io.FileOutputStream;
44

5-
class Student1
6-
{
5+
class Student11 {
76
int rollno;
87
String name;
98
float avg;
@@ -12,7 +11,7 @@ class Student1
1211

1312
public class DataOutputStreamsExample {
1413
public static void main(String[] args)throws Exception {
15-
FileOutputStream fos=new FileOutputStream("C:\\Users\\somes\\Downloads\\JAVA SE\\Section23JavaIOStreams\\Serialisation Storing Data in a File\\MyJAVA\\Student2.txt");
14+
FileOutputStream fos=new FileOutputStream("/Users/somesh/Java SE/JavaEvolution-Learning-Growing-Mastering/Section23JavaIOStreams/src/MyJAVA/Student1.txt");
1615
DataOutputStream dos=new DataOutputStream(fos);
1716

1817
Student1 s1=new Student1();
19 Bytes
Binary file not shown.

0 commit comments

Comments
 (0)