Handling Primitive Data Types in Java I/O जावा I/O में प्रिमिटिव डेटा टाइप्स को संभालना
Java provides special Data Streams to read and write primitive data types like int
, float
, boolean
, and char
.
जावा डाटा स्ट्रीम्स प्रदान करता है जो प्रिमिटिव डेटा टाइप्स जैसे int
, float
, boolean
, और char
को पढ़ने और लिखने के लिए उपयोग होती हैं।
Key Points / मुख्य बिंदु:-
-
DataOutputStream
writes primitive data types to a file.
DataOutputStream
फाइल में प्रिमिटिव डेटा टाइप्स लिखता है। -
DataInputStream
reads primitive data types from a file.
DataInputStream
फाइल से प्रिमिटिव डेटा टाइप्स पढ़ता है। -
These are useful for structured data storage.
यह स्ट्रक्चर्ड डेटा स्टोरेज के लिए उपयोगी हैं।
💻 Example 1: Writing Primitive Data Types
import java.io.*;
public class WritePrimitives {
public static void main(String[] args) {
try {
FileOutputStream fos = new FileOutputStream("data.bin");
DataOutputStream dos = new DataOutputStream(fos);
dos.writeInt(101);
dos.writeUTF("Ajay");
dos.writeFloat(95.5f);
dos.writeBoolean(true);
dos.close();
fos.close();
System.out.println("Primitive data written successfully.");
} catch (IOException e) {
System.out.println("Error writing data.");
}
}
}
Output:
Primitive data written successfully.
💻 Example 2: Reading Primitive Data Types
import java.io.*;
public class ReadPrimitives {
public static void main(String[] args) {
try {
FileInputStream fis = new FileInputStream("data.bin");
DataInputStream dis = new DataInputStream(fis);
int id = dis.readInt();
String name = dis.readUTF();
float marks = dis.readFloat();
boolean status = dis.readBoolean();
dis.close();
fis.close();
System.out.println("ID: " + id);
System.out.println("Name: " + name);
System.out.println("Marks: " + marks);
System.out.println("Status: " + status);
} catch (IOException e) {
System.out.println("Error reading data.");
}
}
}
Output:
ID: 101
Name: Ajay
Marks: 95.5
Status: true
🔹 Real-life Uses / वास्तविक उपयोग
-
Storing structured data like employee records
स्ट्रक्चर्ड डेटा जैसे कर्मचारी रिकॉर्ड स्टोर करना -
Game development for saving game states and scores
गेम डेवलपमेंट में गेम स्टेट और स्कोर सेव करना -
Reading sensor data in IoT applications
IoT एप्लिकेशन में सेंसर डेटा पढ़ना
Comments
Post a Comment