36. DataInputStream trong lập trình java

Trong lập trình Java, DataInputStream là một lớp con của FilterInputStream, nó được sử dụng để đọc các dữ liệu nguyên thủy từ một luồng dữ liệu vào (input stream). DataInputStream cung cấp các phương thức để đọc các kiểu dữ liệu nguyên thủy như int, double, boolean, v.v. từ một luồng byte.

Mục đích chính của DataInputStream là cho phép bạn đọc các kiểu dữ liệu nguyên thủy từ luồng dữ liệu mà không cần phải tự thực hiện việc xử lý các bytes hoặc chuyển đổi giữa các kiểu dữ liệu.

Dưới đây là cú pháp của lớp DataInputStream:

java
public class DataInputStream extends FilterInputStream implements DataInput {
    // Constructors:
    public DataInputStream(InputStream in)

    // Methods:
    public final int read(byte[] b) throws IOException
    public final int read(byte[] b, int off, int len) throws IOException
    public final int read() throws IOException
    public final boolean readBoolean() throws IOException
    public final byte readByte() throws IOException
    public final int readUnsignedByte() throws IOException
    public final short readShort() throws IOException
    public final int readUnsignedShort() throws IOException
    public final char readChar() throws IOException
    public final int readInt() throws IOException
    public final long readLong() throws IOException
    public final float readFloat() throws IOException
    public final double readDouble() throws IOException
    public final String readLine() throws IOException
    public final String readUTF() throws IOException
}

Một số phương thức quan trọng của DataInputStream:

  • readBoolean(): Đọc một giá trị boolean từ luồng.
  • readByte(): Đọc một byte từ luồng.
  • readUnsignedByte(): Đọc một giá trị unsigned byte từ luồng.
  • readShort(): Đọc một giá trị short từ luồng.
  • readUnsignedShort(): Đọc một giá trị unsigned short từ luồng.
  • readChar(): Đọc một ký tự từ luồng.
  • readInt(): Đọc một giá trị integer từ luồng.
  • readLong(): Đọc một giá trị long từ luồng.
  • readFloat(): Đọc một giá trị float từ luồng.
  • readDouble(): Đọc một giá trị double từ luồng.
  • readUTF(): Đọc một chuỗi dạng UTF-8 từ luồng.

Chú ý rằng, việc sử dụng DataInputStream yêu cầu bạn phải biết trước cách dữ liệu đã được ghi vào luồng (ví dụ: dùng DataOutputStream để ghi dữ liệu) để đọc chính xác các giá trị nguyên thủy tương ứng.

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top