개인참고자료/자바(네트워크)

바이트 기반 스트림 - DataInputStream과 DataOutputStream

경진 2008. 7. 13. 17:05
DataInputStream과 DataOutputStream

DataInputStream과 DataOutputStream은 자바의 기본형 데이터인 int, float, double, boolan, short, byte 등의 정보를 입력하고 출력하는 데 알맞은 클래스다.

DataInputStream은 생성자에서 InputStream을 받아들이며, DataOutputStream은 생성자에서 OutputStream을 받아들인다. 이는 다른 바이트 스트림을 통해서 읽어 들이거나 쓴다.

자바 IO 클래스는 생성자가 중요한 역할을 한다.
생성자에서 어떤 것을 지정했느냐에 따라서 읽어 들야할 대상과 써야할 대상이 틀려지기 때문이다.

DataInputStream과 DataOutputStream이 각각 InputStream과 OutputStream을 받아들인다는 것은 InpustStream의 자식 클래스, OutputStream의 자식 클래스나 자손 클래스를 받아들인다.

※ InputStream을 인자로 받아들인다는 것은 InputStream의 자식이나 자손의 클래스를 받아들인다.

DataInputStream 생성자

생성자 설명
DataInputStream (InputStream inputStream) InputStream을 인자로 DataInputStream을 생성한다.

DataInputStream 생성자의 추가 메소드

메소드 설명
boolean readBoolean()
throws IOException
스트림으로부터 읽은 boolean을 반환한다.
byte readByte()
throws IOException
스트림으로부터 읽은 byte을 반환한다.
char readChar()
throws IOException
스트림으로부터 읽은 char을 반환한다.
double readDouble()
throws IOException
스트림으로부터 읽은 double을 반환한다.
float readFloat()
throws IOException
스트림으로부터 읽은 float을 반환한다.
long readLong()
throws IOException
스트림으로부터 읽은 long을 반환한다.
short readShort()
throws IOException
스트림으로부터 읽은 short을 반환한다.
int readInt()
throws IOException
스트림으로부터 읽은 int을 반환한다.
void readFully(byte buf[])
throws IOException
스트림으로부터 buf 크기만큼의 바이트를 읽어 buf에 저장한다.
String readUTF()
throws IOException
UTF 인코딩 값을 얻어 문자열로 반환한다. 네트워크 프로그래밍을 할 때,
네트워크로부터 문자열을 읽어 들일 때 많이 사용한다.

DataOutputStream 생성자

생성자 설명
DataOutputStream (OutputStream outputStream) OutputStream을 인자로 DataOutputStream을 생성한다.

DataOutputStream 생성자의 추가 메소드

메소드 설명
void write(int i)
throws IOException
int형 i 값이 갖는 1바이트를 출력한다.
void write(byte buf[]
, int index, int size)
throws IOException
바이트 배열 buf의 주어진 위치 index에서 size만큼 출력한다.
void writeBoolean(boolean b)
throws IOException
boolean을 1바이트 값으로 출력한다.
void writeByte(int i)
throws IOException
int를 4바이트 값으로 상위 바이트 먼저 출력한다.
void writeBytes(String s)
throws IOException
문자열을 바이트순으로 출력한다.
void writeChar(int i)
throws IOException
char를 2바이트 값으로 상위 바이트를 먼저 출력한다.
void writeDouble(double d)
throws IOException
Double 클래스의 doubleToBits()를 사용해서 long으로 변환한 다음 long 값을 8바이트 수량으로 상위 바이트 먼저 출력한다.
void writeFloat(float f)
throws IOException
Float를 floatToBits()를 사용해서 변환한 후, int 값을 4바이트 수량으로 상위 바이트 먼저 출력한다.
void writeInt(int i)
throws IOException
int의 상위 바이트를 먼저 출력한다.
void writeLong(long l)
throws IOException
long형의 인자 값을 출력한다.
void writeShort(short s)
throws IOException
short형의 인자 값을 출력한다.
void writeUTF(String s)
throws IOException
UTF-8 인코딩을 사용해서 문자열을 출력한다.
네트워크 프로그래밍을 할 때, 문자열 전송 시에 자주 사용한다.