산업 제조
산업용 사물 인터넷 | 산업자재 | 장비 유지 보수 및 수리 | 산업 프로그래밍 |
home  MfgRobots >> 산업 제조 >  >> Industrial programming >> java

자바 FileInputStream 클래스

자바 FileInputStream 클래스

이 자습서에서는 예제를 통해 Java FileInputStream 및 해당 메서드에 대해 알아봅니다.

FileInputStream java.io 클래스 패키지는 파일에서 데이터(바이트 단위)를 읽는 데 사용할 수 있습니다.

InputStream 확장 추상 클래스.

FileInputStream에 대해 알아보기 전에 , Java Files에 대해 알고 있어야 합니다.

<시간>

FileInputStream 생성

파일 입력 스트림을 생성하려면 java.io.FileInputStream을 가져와야 합니다. 먼저 패키지. 패키지를 가져온 후 Java에서 파일 입력 스트림을 만드는 방법은 다음과 같습니다.

1. 파일 경로 사용

FileInputStream input = new FileInputStream(stringPath);

여기에서 path로 지정된 파일에 연결될 입력 스트림을 만들었습니다. .

2. 파일의 개체 사용

FileInputStream input = new FileInputStream(File fileObject);

여기에서 fileObject로 지정된 파일에 연결될 입력 스트림을 만들었습니다. .

<시간>

FileInputStream의 메소드

FileInputStream 클래스는 InputStream에 있는 다양한 메서드에 대한 구현을 제공합니다. 수업.

read() 메소드

input.txt라는 파일이 있다고 가정합니다. 다음 내용으로.

This is a line of text inside the file.

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();
     }
  }
}

출력

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

위의 예에서 input이라는 파일 입력 스트림을 만들었습니다. . 입력 스트림은 input.txt와 연결됩니다. 파일.

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

파일에서 데이터를 읽기 위해 read()를 사용했습니다. while 루프 내부의 메소드입니다.

<시간>

available() 메서드

사용 가능한 바이트 수를 얻으려면 available()를 사용할 수 있습니다. 방법. 예를 들어,

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();
      }
   }
}

출력

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

위의 예에서

  1. 먼저 available()를 사용합니다. 파일 입력 스트림에서 사용 가능한 바이트 수를 확인하는 메서드입니다.
  2. 그런 다음 read()를 사용했습니다. 파일 입력 스트림에서 3바이트를 읽는 방법 3번.
  3. 이제 바이트를 읽은 후 사용 가능한 바이트를 다시 확인했습니다. 이번에는 사용 가능한 바이트가 3으로 감소했습니다.
<시간>

skip() 메서드

지정된 바이트 수를 버리고 건너뛰려면 skip()을 사용할 수 있습니다. 방법. 예를 들어,

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();
      }
   }
}

출력

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

위의 예에서는 skip()을 사용했습니다. 파일 입력 스트림에서 5바이트의 데이터를 건너뛰는 방법입니다. 따라서 "This " 텍스트를 나타내는 바이트 입력 스트림에서 읽지 않습니다.

<시간>

close() 메소드

파일 입력 스트림을 닫으려면 close()를 사용할 수 있습니다. 방법. close() 메소드가 호출되면 입력 스트림을 사용하여 데이터를 읽을 수 없습니다.

위의 모든 예에서는 close()을 사용했습니다. 파일 입력 스트림을 닫는 메소드입니다.

<시간>

FileInputStream의 다른 메서드

메소드 설명
finalize() close() 메소드 호출
getChannel() FileChannel의 개체를 반환합니다. 입력 스트림과 연결
getFD() 입력 스트림과 관련된 파일 설명자를 반환합니다.
mark() 입력 스트림에서 데이터를 읽은 위치 표시
reset() 표시가 설정된 입력 스트림의 지점으로 컨트롤을 반환합니다.

자세한 내용은 Java FileInputStream(공식 Java 설명서)을 참조하십시오.


java

  1. 자바 최종 키워드
  2. 자바 instanceof 연산자
  3. 자바 중첩 정적 클래스
  4. 자바 익명 클래스
  5. 자바 싱글톤 클래스
  6. 자바 리플렉션
  7. 자바 ObjectOutputStream 클래스
  8. 자바 BufferedReader 클래스
  9. 자바 스캐너 클래스
  10. 자바 제네릭