Myo-Kyeong Tech Blog

[ JAVA ] FileInputStream 확장하여 DataInputStream 클래스 구현하기 ( java.io.DataInputStream ) 본문

Programming/Java

[ JAVA ] FileInputStream 확장하여 DataInputStream 클래스 구현하기 ( java.io.DataInputStream )

myo-kyeong 2023. 6. 29. 17:39
728x90

java.io.DataInputStream 설명 

 

'FileInputStream' 클래스는 파일의 내용을 바이트 단위로 읽어들이는 기능을 제공합니다.

['FileInputStream'만을 사용하는 경우]

try {
    FileInputStream fis = new FileInputStream("data.bin");

    int i = fis.read();
    i = i << 8;
    i = i | fis.read();
    
    System.out.println(i);

    fis.close();
} catch (IOException e) {
    e.printStackTrace();
}


위의 예시에서 볼 수 있듯이, 두 바이트를 읽어서 하나의 정수를 생성하는 과정은 수동으로 진행되고 있습니다.
 'read()' 메서드를 두 번 호출하여 두 개의 바이트를 읽은 후, 이들을 결합하여 하나의 정수를 만드는 작업이 필요합니다. 이 과정은 개발자에게 추가적인 코딩을 요구하며, 그로 인해 코드가 복잡해질 수 있습니다.

 

[DataInputStream을 사용하는 경우]

try {
    DataInputStream dis = new DataInputStream(new FileInputStream("data.bin"));

    int i = dis.readInt();

    System.out.println(i);

    dis.close();
} catch (IOException e) {
    e.printStackTrace();
}

 

 

'DataInputStream'을 사용하면, 'readInt()' 메서드를 통해 직접 정수를 읽어올 수 있습니다. 이 메서드는 내부적으로 필요한 바이트 수를 읽어서 정수를 반환하므로, 개발자는 복잡한 바이트 조작 없이 필요한 데이터 타입을 바로 얻을 수 있습니다.

이렇게 'DataInputStream'은 기본 데이터 타입을 효과적으로 읽을 수 있는 메소드들을 추가로 제공합니다. 즉, FileInputStream이 바이트 단위로 데이터를 읽어들이는 반면, DataInputStream은 기본 데이터 타입(int, long, float, double, boolean 등)을 직접 읽어들일 수 있는 기능을 제공합니다.

예를 들어, readInt(), readLong(), readBoolean(), readChar(), readDouble(), readFloat(), readShort(), readUTF() 등의 메소드들이 있습니다. 이런 메소드들을 이용하면, 개발자는 각 데이터 타입에 맞게 데이터를 읽을 수 있으며, 이는 개발자의 부담을 줄여주며 코드의 가독성을 향상시킵니다.

 

java.io.DataInputStream 코드 구현

 

package bitcamp.io;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;

public class DataInputStream extends FileInputStream {

  public DataInputStream(String name) throws FileNotFoundException {
    super(name);
  }

  public short readShort() throws IOException {
    return (short)(this.read() << 8 | this.read());
  }

  public int readInt() throws IOException {
    return this.read() << 24 | this.read() << 16 | this.read() << 8 | this.read();
  }

  public long readLong() throws IOException {
    return (long)this.read() << 56
        | (long)this.read() << 48
        | (long)this.read() << 40
        | (long)this.read() << 32
        | (long)this.read() << 24
        | (long)this.read() << 16
        | (long)this.read() << 8
        | this.read();
  }

  public char readChar() throws IOException {
    return (char)(this.read() << 8 | this.read());
  }

  public String readUTF() throws IOException {
    int length = this.read() << 8 | this.read();
    byte[] buf = new byte[length];
    this.read(buf);
    return new String(buf, "UTF-8");
  }

}

 

728x90