Lớp Java BufferedInputStream

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

Các BufferedInputStreamlớp của java.iogói phần mềm được sử dụng với các dòng đầu vào khác để đọc dữ liệu (tính theo byte) một cách hiệu quả hơn.

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

Hoạt động của BufferedInputStream

Các BufferedInputStreamduy trì một nội bộ đệm của 8192 byte .

Trong quá trình đọc trong BufferedInputStream, một đoạn byte được đọc từ đĩa và được lưu trữ trong bộ đệm bên trong. Và từ các byte đệm bên trong được đọc riêng lẻ.

Do đó, số lượng thông tin liên lạc đến đĩa bị giảm. Đây là lý do tại sao đọc byte nhanh hơn bằng cách sử dụng BufferedInputStream.

Tạo một dòng BufferedInputStream

Để tạo một BufferedInputStreamjava.io.BufferedInputStreamtrước tiên chúng ta phải nhập gói. 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 FileInputStream
FileInputStream file = new FileInputStream(String path);

// Creates a BufferedInputStream
BufferedInputStream buffer = new BufferInputStream(file);

Trong ví dụ trên, chúng ta đã tạo một vùng đệmBufferdInputStream được đặt tên với tệp được đặt tên .FileInputStream

Ở đây, bộ đệm bên trong có kích thước mặc định là 8192 byte. Tuy nhiên, chúng tôi cũng có thể chỉ định kích thước của bộ đệm bên trong.

// Creates a BufferedInputStream with specified size internal buffer
BufferedInputStream buffer = new BufferInputStream(file, int size);

Bộ đệm sẽ giúp đọc byte từ tệp nhanh hơn.

Phương thức BufferedInputStream

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

phương thức read ()

  • read() – reads a single byte from the input stream
  • read(byte[] arr) – reads bytes from the stream and stores in the specified array
  • read(byte[] arr, int start, int length) – reads the number of bytes equal to the length from the stream and stores in the specified array starting from the position start

Giả sử chúng ta có một tệp tên input.txt với nội dung như sau.

This is a line of text inside the file.

Hãy thử đọc tệp bằng cách sử dụng BufferedInputStream.

import java.io.BufferedInputStream;
import java.io.FileInputStream;

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

            // Creates a FileInputStream
            FileInputStream file = new FileInputStream("input.txt");

            // Creates a BufferedInputStream
            BufferedInputStream input = new BufferedInputStream(file);

            // Reads first byte from file
            int i = input .read();

            while (i != -1) {
                System.out.print((char) i);

                // Reads next byte from the file
                i = input.read();
            }
            input.close();
        }

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

Đầu ra

This is a line of text inside the file.

Trong ví dụ trên, chúng ta đã tạo một luồng đầu vào được đệm có tên là buffer cùng với FileInputStream. Luồng đầu vào được liên kết với tệp input.txt .

FileInputStream file = new FileInputStream("input.txt");
BufferedInputStream buffer = new BufferedInputStream(file);

Ở đây, chúng tôi đã sử dụng read()phương pháp để đọc một mảng byte từ bộ đệm bên trong của bộ đọc đệm.

phương thức sẵn có ()

Để lấy số byte có sẵn trong luồng đầu vào, chúng ta có thể sử dụng available()phương pháp. Ví dụ,

import java.io.FileInputStream;
import java.io.BufferedInputStream;

public class Main {

   public static void main(String args[]) {

      try {

         // Suppose, the input.txt file contains the following text
         // This is a line of text inside the file.
         FileInputStream file = new FileInputStream("input.txt");
         
         // Creates a BufferedInputStream
         BufferedInputStream buffer = new BufferedInputStream(file);

         // Returns the available number of bytes
         System.out.println("Available bytes at the beginning: " + buffer.available());

         // Reads bytes from the file
         buffer.read();
         buffer.read();
         buffer.read();

         // Returns the available number of bytes
         System.out.println("Available bytes at the end: " + buffer.available());

         buffer.close();
      }

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

Đầu ra

Available bytes at the beginning: 39
Available bytes at the end: 36

Trong ví dụ trên,

  1. Đầu tiên chúng tôi sử dụng available()phương pháp để kiểm tra số lượng byte có sẵn trong luồng đầu vào.
  2. Sau đó, chúng tôi đã sử dụng read()phương pháp 3 lần để đọc 3 byte từ luồng đầu vào.
  3. Bây giờ, sau khi đọc các byte, chúng tôi lại kiểm tra các byte có sẵn. Lần này số byte khả dụng giảm đi 3.

phương thức bỏ qua ()

Để loại bỏ và bỏ qua số byte được chỉ định, chúng ta có thể sử dụng skip()phương pháp này. Ví dụ,

import java.io.FileInputStream;
import java.io.BufferedInputStream;

public class Main {

   public static void main(String args[]) {

      try {
         // Suppose, the input.txt file contains the following text
         // This is a line of text inside the file.
         FileInputStream file = new FileInputStream("input.txt");

         // Creates a BufferedInputStream
         BufferedInputStream buffer = new BufferedInputStream(file);

         // Skips the 5 bytes
         buffer.skip(5);
         System.out.println("Input stream after skipping 5 bytes:");

         // Reads the first byte from input stream
         int i = buffer.read();
         while (i != -1) {
            System.out.print((char) i);

            // Reads next byte from the input stream
            i = buffer.read();
         }

         // Closes the input stream
         buffer.close();
      }

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

Đầu ra

Input stream after skipping 5 bytes: is a line of text inside the file.

Trong ví dụ trên, chúng tôi đã sử dụng skip()phương pháp để bỏ qua 5 byte từ luồng đầu vào tệp. Do đó, các byte 'T''h''i''s'và ' 'được bỏ qua từ dòng đầu vào.

phương thức close ()

Để đóng luồng đầu vào được đệm, chúng ta có thể sử dụng close()phương pháp này. Khi close()phương thức được gọi, chúng ta không thể sử dụng luồng đầu vào để đọc dữ liệu.

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

MethodsDecfscriptions
mark()mark 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

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









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