Lớp Java FileInputStream

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

Các FileInputStreamlớp của java.iogói có thể được sử dụng để đọc dữ liệu (tính theo byte) từ các tập tin.

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

Trước khi chúng ta tìm hiểu về FileInputStream, hãy chắc chắn rằng bạn đã biết về Tệp Java .

Tạo một FileInputStream

Để tạo luồng đầu vào tệp, java.io.FileInputStreamtrướ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 nhập tệp trong Java.

1. Sử dụng đường dẫn đến tệp

FileInputStream input = new FileInputStream(stringPath);

Ở đây, chúng tôi đã tạo một luồng đầu vào sẽ được liên kết với tệp được chỉ định bởi đường dẫn .

2. Sử dụng một đối tượng của tệp

FileInputStream input = new FileInputStream(File fileObject);

Ở đây, chúng tôi đã tạo một luồng đầu vào sẽ được liên kết với tệp được chỉ định bởi fileObject.

Phương thức của FileInputStream

Các FileInputStreamlớ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 file
  • read(byte[] array) – reads the bytes from the file and stores in the specified array
  • read(byte[] array, int start, int length) – reads the number of bytes equal to length from the file 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 này bằng cách sử dụng FileInputStream.

import java.io.FileInputStream;

public class Main {

  public static void main(String args[]) {

     try {
        FileInputStream input = new FileInputStream("input.txt");

        System.out.println("Data in the file: ");

        // Reads the first byte
        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

Data in the file:
This is a line of text inside the file.

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

FileInputStream input = new FileInputStream("input.txt");

Để đọc dữ liệu từ tệp, chúng tôi đã sử dụng read()phương thức bên trong vòng lặp while.

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

Để lấy số byte có sẵn, chúng ta có thể sử dụng available()phương pháp. Ví dụ,

import java.io.FileInputStream;

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 input = new FileInputStream("input.txt");

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

         // Reads 3 bytes from the file
         input.read();
         input.read();
         input.read();

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

         input.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. Trước 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 nhập tệp.
  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 tệp.
  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;

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 input = new FileInputStream("input.txt");

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

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

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

         // close() method
         input.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 dữ liệu từ luồng đầu vào tệp. Do đó, các byte đại diện cho văn bản “This” không được đọc từ luồng đầu vào.

phương thức close ()

Để đóng luồng nhập tệp, chúng ta có thể sử dụng close()phương pháp. 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.

Trong tất cả các ví dụ trên, chúng tôi đã sử dụng close()phương pháp để đóng luồng đầu vào tệp.

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

MethodsDecfscriptions
finalize()ensures that the close() method is called
getChannel()returns the object of FileChannel associated with the input stream
getFD()returns the file decfscriptor associated with the input stream
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 FileInputStream (tài liệu Java chính thức) .









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