Lớp Java ObjectInputStream

Trong hướng dẫn này, chúng ta sẽ tìm hiểu về Java ObjectOutputStream và các phương thức của nó với sự trợ giúp của các ví dụ.

Các ObjectInputStreamlớp của java.iogói có thể được sử dụng để đọc các đối tượng mà trước đây được viết bởi ObjectOutputStream.

Nó mở rộng InputStreamlớp trừu tượng.

Trước khi bạn tìm hiểu về ObjectInputStreamlớp, hãy đảm bảo rằng bạn biết về Lớp ObjectOutputStream .

Hoạt động của ObjectInputStream

Chủ ObjectInputStreamyếu được sử dụng để đọc dữ liệu được viết bởi ObjectOutputStream.

Về cơ bản, các ObjectOutputStreamchuyển đổi các đối tượng Java thành các luồng tương ứng. Điều này được gọi là tuần tự hóa. Các luồng được chuyển đổi đó có thể được lưu trữ trong các tệp hoặc chuyển qua mạng.

Bây giờ, nếu chúng ta cần đọc các đối tượng đó, chúng ta sẽ sử dụng các đối tượng ObjectInputStreamđó sẽ chuyển đổi các luồng trở lại các đối tượng tương ứng. Điều này được gọi là deserialization.

Tạo một ObjectInputStream

Để tạo luồng đầu vào đối tượng, java.io.ObjectInputStreamtrước tiên chúng ta phải nhập gói. Sau khi chúng tôi nhập gói, đây là cách chúng tôi có thể tạo luồng đầu vào.

// Creates a file input stream linked with the specified file
FileInputStream fileStream = new FileInputStream(String file);

// Creates an object input stream using the file input stream
ObjectInputStream objStream = new ObjectInputStream(fileStream);

Trong ví dụ trên, chúng ta đã tạo một luồng nhập đối tượng có tên là objStream được liên kết với luồng nhập tệp có tên là fileStream .

Bây giờ, objStreamcó thể được sử dụng để đọc các đối tượng từ tệp.

Các phương thức của ObjectInputStream

Các ObjectInputStreamlớp học cung cấp triển khai các phương pháp khác nhau trình bày trong InputStreamlớp.

phương thức read ()

  • read() – reads a byte of data from the input stream
  • readBoolean() – reads data in boolean form
  • readChar() – reads data in character form
  • readInt() – reads data in integer form
  • readObject() – reads the object from the input stream

Ví dụ 1: Java ObjectInputStream

Hãy xem cách chúng ta có thể sử dụng ObjectInputStreamlớp để đọc các đối tượng được viết bởi ObjectOutputStreamlớp.

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;

class Main {
    public static void main(String[] args) {

        int data1 = 5;
        String data2 = "This is programiz";

        try {
            FileOutputStream file = new FileOutputStream("file.txt");
            ObjectOutputStream output = new ObjectOutputStream(file);

            // Writing to the file using ObjectOutputStream
            output.writeInt(data1);
            output.writeObject(data2);

            FileInputStream fileStream = new FileInputStream("file.txt");
            // Creating an object input stream
            ObjectInputStream objStream = new ObjectInputStream(fileStream);

            //Using the readInt() method
            System.out.println("Integer data :" + objStream.readInt());

            // Using the readObject() method
            System.out.println("String data: " + objStream.readObject());

            output.close();
            objStream.close();
        }
        catch (Exception e) {
            e.getStackTrace();
        }
    }
}

Đầu ra

Integer data: 5
String data: This is programiz

Trong ví dụ trên, chúng ta đã sử dụng phương thức readInt()và readObject()để đọc dữ liệu số nguyên và dữ liệu đối tượng từ tệp.

Ở đây, chúng tôi đã sử dụng ObjectOutputStreamđể ghi dữ liệu vào tệp. Sau đó, chúng tôi đọc dữ liệu từ tệp bằng cách sử dụng ObjectInputStream.

Ví dụ 2: Java ObjectInputStream

Hãy xem một ví dụ thực tế khác,

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;

class Dog implements Serializable {

    String name;
    String breed;

    public Dog(String name, String breed) {
        this.name = name;
        this.breed = breed;
    }
}

class Main {
    public static void main(String[] args) {

        // Creates an object of Dog class
        Dog dog = new Dog("Tyson", "Labrador");

        try {
            FileOutputStream file = new FileOutputStream("file.txt");

            // Creates an ObjectOutputStream
            ObjectOutputStream output = new ObjectOutputStream(file);

            // Writes objects to the output stream
            output.writeObject(dog);

            FileInputStream fileStream = new FileInputStream("file.txt");

            // Creates an ObjectInputStream
            ObjectInputStream input = new ObjectInputStream(fileStream);

            // Reads the objects
            Dog newDog = (Dog) input.readObject();

            System.out.println("Dog Name: " + newDog.name);
            System.out.println("Dog Breed: " + newDog.breed);

            output.close();
            input.close();
        }

        catch (Exception e) {
            e.getStackTrace();
        }
    }
}

Đầu ra

Dog Name: Tyson
Dog Breed: Labrador

Trong ví dụ trên, chúng tôi đã tạo

  • ObjectOutputStream named output using the FileOutputStream named file
  • ObjectInputStream named input using the FileInputStream named fileStream
  • An object dog of the Dog class

Ở đây, chúng ta đã sử dụng luồng xuất đối tượng để ghi đối tượng vào tệp. Và, luồng đầu vào đối tượng để đọc đối tượng từ tệp.

Lưu ý : Lớp Dog thực hiện Serializablegiao diện. Đó là bởi vì ObjectOutputStreamchỉ ghi các đối tượng có thể tuần tự hóa vào luồng đầu ra.

Các phương pháp khác của ObjectInputStream

MethodsDecfscriptions
available()returns the available number of bytes in the input stream
mark()marks the position in input stream up to which data has been read
reset()returns the control to the point in the input stream where the mark was set
skipBytes()skips and discards the specified bytes from the input stream
close()closes the object input stream

Để tìm hiểu thêm, hãy truy cập Java ObjectInputStream (tài liệu Java chính thức) .









Gõ tìm kiếm nhanh...