Reading and Writing Bytes in Java / जावा में बाइट्स पढ़ना और लिखना
Java provides Byte Streams to handle 8-bit data (bytes) for reading and writing files.
जावा बाइट स्ट्रीम्स प्रदान करता है, जो 8-बिट डेटा (बाइट्स) को फाइल से पढ़ने और लिखने के लिए प्रयोग होती हैं।
Key Points / मुख्य बिंदु:-
-
Use
FileInputStream
for reading bytes from a file.
फाइल से बाइट्स पढ़ने के लिएFileInputStream
का उपयोग करें। -
Use
FileOutputStream
for writing bytes to a file.
फाइल में बाइट्स लिखने के लिएFileOutputStream
का उपयोग करें। -
Suitable for binary files like images, PDFs, and videos.
यह बाइनरी फाइल्स जैसे इमेज, PDF और वीडियो के लिए उपयुक्त है।
💻 Example 1: Writing Bytes to a File
import java.io.FileOutputStream;
import java.io.IOException;
public class WriteBytesExample {
public static void main(String[] args) {
try {
FileOutputStream fos = new FileOutputStream("bytefile.txt");
String data = "Hello Byte Stream!";
fos.write(data.getBytes());
fos.close();
System.out.println("Bytes written successfully.");
} catch (IOException e) {
System.out.println("Error writing file.");
}
}
}
Output:
Bytes written successfully.
bytefile.txt content:
Hello Byte Stream!
💻 Example 2: Reading Bytes from a File
import java.io.FileInputStream;
import java.io.IOException;
public class ReadBytesExample {
public static void main(String[] args) {
try {
FileInputStream fis = new FileInputStream("bytefile.txt");
int i;
while ((i = fis.read()) != -1) {
System.out.print((char) i);
}
fis.close();
} catch (IOException e) {
System.out.println("Error reading file.");
}
}
}
Output:
Hello Byte Stream!
🔹 Real-life Uses / वास्तविक उपयोग
-
Reading and writing binary files like images, audio, or video
इमेज, ऑडियो या वीडियो जैसी बाइनरी फाइल्स को पढ़ने और लिखने में -
File transfer operations
फाइल ट्रांसफर ऑपरेशन्स -
Handling large files in raw byte format
रॉ बाइट फॉर्मेट में बड़ी फाइल्स हैंडल करना
Comments
Post a Comment