Showing posts with label Java Byte Stream. Show all posts
Showing posts with label Java Byte Stream. Show all posts

Monday, August 4, 2025

Reading and Writing Bytes in Java / जावा में बाइट्स पढ़ना और लिखना

Java provides Byte Streams to handle 8-bit data (bytes) for reading and writing files.

जावा बाइट स्ट्रीम्स प्रदान करता है, जो 8-बिट डेटा (बाइट्स) को फाइल से पढ़ने और लिखने के लिए प्रयोग होती हैं।

Key Points / मुख्य बिंदु:-

  1. Use FileInputStream for reading bytes from a file.
    फाइल से बाइट्स पढ़ने के लिए FileInputStream का उपयोग करें।

  2. Use FileOutputStream for writing bytes to a file.
    फाइल में बाइट्स लिखने के लिए FileOutputStream का उपयोग करें।

  3. 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
    रॉ बाइट फॉर्मेट में बड़ी फाइल्स हैंडल करना

Byte Stream in Java जावा में बाइट स्ट्रीम

Byte Stream in Java is used to read and write 8-bit binary data like files, images, audio, and video.

जावा में बाइट स्ट्रीम का उपयोग 8-बिट बाइनरी डेटा को पढ़ने और लिखने के लिए किया जाता है, जैसे फाइल, इमेज, ऑडियो और वीडियो। बाइट स्ट्रीम दो प्रकार की होती हैं:-

  1. InputStream (इनपुट स्ट्रीम)

  2. OutputStream (आउटपुट स्ट्रीम)


1️⃣ InputStream (इनपुट स्ट्रीम)

InputStream is a superclass that reads data from a source like file, device, or socket.
InputStream एक सुपरक्लास है जो डेटा को किसी स्त्रोत (फाइल, डिवाइस, या सॉकेट) से पढ़ती है।

🔹 Common Methods of InputStream

Method Description (English) विवरण (Hindi)
int read()          Reads next byte of data                       अगली बाइट को पढ़ता है
int available() Returns number of available bytes उपलब्ध बाइट्स की संख्या लौटाता है
void close() Closes the stream स्ट्रीम को बंद करता है

2️⃣ OutputStream (आउटपुट स्ट्रीम)

OutputStream is a superclass that writes data to a destination like file, device, or socket.
OutputStream एक सुपरक्लास है जो डेटा को किसी गंतव्य (फाइल, डिवाइस, या सॉकेट) में लिखती है।

🔹 Common Methods of OutputStream

Method      Description (English) विवरण (Hindi)
void write(int)           Writes a byte                       एक बाइट लिखता है
void write(byte[]) Writes byte array बाइट ऐरे लिखता है
void flush() Flushes the stream स्ट्रीम को रिफ्रेश करता है
void close() Closes the stream स्ट्रीम को बंद करता है

3️⃣ Important Byte Stream Classes

Class Name Description (English) विवरण (Hindi)
FileInputStream Reads byte data from file फाइल से बाइट डेटा पढ़ता है
FileOutputStream Writes byte data to file फाइल में बाइट डेटा लिखता है
BufferedInputStream Reads data using buffer बफर के साथ पढ़ता है
BufferedOutputStream Writes data using buffer बफर के साथ लिखता है
DataInputStream Reads primitive data types प्रिमिटिव डेटा पढ़ता है
DataOutputStream Writes primitive data types प्रिमिटिव डेटा लिखता है
PrintStream Writes formatted output फॉर्मेटेड आउटपुट लिखता है

4️⃣ Byte Stream Examples

📝 Example 1: Read File using BufferedInputStream

import java.io.*;

public class Sample {
    public static void main(String args[]) {
        try {
            FileInputStream fis = new FileInputStream("file.txt");
            BufferedInputStream bis = new BufferedInputStream(fis);
            int i;
            while((i = bis.read()) != -1) {
                System.out.print((char)i);
            }
            bis.close();
            fis.close();
        } catch(FileNotFoundException e1) {
            System.out.println("File not found");
        } catch(Exception e2) {
            System.out.println("Reading file error");
        }
    }
}

Output:

Example for BufferedInputStream.

📝 Example 2: Write File using BufferedOutputStream

import java.io.*;

public class Sample {
    public static void main(String args[]) {
        try {
            FileOutputStream fos = new FileOutputStream("file1.txt");
            BufferedOutputStream bos = new BufferedOutputStream(fos);
            String str = "Example for BufferedOutputStream.";
            bos.write(str.getBytes());
            bos.close();
            fos.close();
            System.out.println("File is created successfully");
        } catch(Exception e) {
            System.out.println("File is not created");
        }
    }
}

📝 Example 3: Write Primitive Data using DataOutputStream

import java.io.*;

public class Sample {
    public static void main(String args[]) {
        int id = 1;
        String name = "Ajay Tiwari";
        float salary = 25000.50f;
        try {
            FileOutputStream fos = new FileOutputStream("file.txt");
            DataOutputStream dos = new DataOutputStream(fos);
            dos.writeInt(id);
            dos.writeUTF(name);
            dos.writeFloat(salary);
            dos.close();
            System.out.println("Data written successfully.");
        } catch(IOException e) {
            System.out.println(e);
        }
    }
}

📝 Example 4: Read Primitive Data using DataInputStream

import java.io.*;

class Sample1 {
    public static void main(String[] args) {
        try {
            FileInputStream fis = new FileInputStream("file.txt");
            DataInputStream dis = new DataInputStream(fis);
            System.out.println("ID : " + dis.readInt());
            System.out.println("Name : " + dis.readUTF());
            System.out.println("Salary : " + dis.readFloat());
        } catch(IOException e) {
            System.out.println(e);
        }
    }
}

Output:

ID : 1
Name : Ajay Tiwari
Salary : 25000.50

📝 Example 5: Simple File Write using FileOutputStream

import java.io.*;

public class Sample {
    public static void main(String args[]) {
        try {
            FileOutputStream fos = new FileOutputStream("file.txt");
            String str = "Hello World!";
            fos.write(str.getBytes());
            fos.close();
            System.out.println("File written successfully");
        } catch(Exception e) {
            System.out.println(e);
        }
    }
}

📝 Example 6: Simple File Read using FileInputStream

import java.io.*;

public class Sample {
    public static void main(String args[]) {
        try {
            FileInputStream fis = new FileInputStream("file.txt");
            int i;
            while((i = fis.read()) != -1) {
                System.out.print((char)i);
            }
            fis.close();
        } catch(Exception e) {
            System.out.println(e);
        }
    }
}

📝 Example 7: Write File using PrintStream

import java.io.*;

public class Sample {
    public static void main(String args[]) {
        try {
            FileOutputStream fos = new FileOutputStream("file.txt");
            PrintStream ps = new PrintStream(fos);
            ps.println("Hello World!");
            ps.close();
            fos.close();
            System.out.println("Data Written Successfully");
        } catch(Exception e) {
            System.out.println(e);
        }
    }
}

Output:

Hello World!

📚 Other Stream Classes in Java जावा में अन्य स्ट्रीम क्लासेस

In Java, apart from basic byte and character streams, there are several specialized stream classes that provide advanced input-output operat...