Skip to content

Commit 4b77d1b

Browse files
committed
feat: add DataInputStream-based deserialization with Student1 example
WHAT: - Created `Student1` class with fields: rollno, name, dept, avg. - Implemented `DataInputStreamsExample2` to read student data from file `Student2.txt` using `DataInputStream`. HOW: 1. Opened file via `FileInputStream` and wrapped in `DataInputStream`. 2. Instantiated `Student1` object. 3. Read data in the same sequence as written: - readInt() → rollno - readUTF() → name - readUTF() → dept - readFloat() → avg 4. Printed student details to the console. 5. Properly closed the input stream. KEY POINTS: - **Order matters:** Data must be read in the same order and type in which it was written, otherwise runtime errors occur. - `DataInputStream` simplifies reading Java primitives and strings without manual parsing. - Complements `DataOutputStream` for serialization. REAL-WORLD APPLICATIONS: - Custom serialization format for performance-sensitive apps. - Storing and retrieving structured student or employee records. - Lightweight persistence layer for local file-based storage. - Useful in games, logging, or legacy system integrations. IMPROVEMENTS: - Use try-with-resources for auto-closing streams. - Add validation/error handling if file data is corrupted. - Add corresponding `DataOutputStream` writer to complete the cycle. Signed-off-by: https://github.com/Someshdiwan <[email protected]>
1 parent 7ab1469 commit 4b77d1b

File tree

2 files changed

+33
-0
lines changed

2 files changed

+33
-0
lines changed
Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
1+
import java.io.*;
2+
3+
class Student1 {
4+
int rollno;
5+
String name;
6+
String dept;
7+
float avg;
8+
}
9+
10+
public class DataInputStreamsExample2 {
11+
public static void main(String[] args) throws Exception {
12+
FileInputStream fis = new FileInputStream("/Users/somesh/Java SE/JavaEvolution-Learning-Growing-Mastering/Section23JavaIOStreams/src/MyJAVA/Student2.txt");
13+
DataInputStream dis = new DataInputStream(fis);
14+
15+
// Serialisation: using DataInput and DataOutput Streams.
16+
17+
Student1 s = new Student1();
18+
19+
s.rollno = dis.readInt();
20+
s.name = dis.readUTF();
21+
s.dept = dis.readUTF();
22+
s.avg = dis.readFloat();
23+
24+
// Order Must be same. to read the data in the file using Input Stream.
25+
26+
System.out.println("Roll No: " + s.rollno);
27+
System.out.println("Name: " + s.name);
28+
System.out.println("Average: " + s.avg);
29+
System.out.println("Dept: " + s.dept);
30+
31+
dis.close();
32+
}
33+
}
40 Bytes
Binary file not shown.

0 commit comments

Comments
 (0)