inputStream을 읽을때 필요한 데이터를 모두 읽을때까지 대기하는 코드
result값으로 1024byte이하의 데이터가 전송되고 스트림이 종료되는 시나리오까지 고려한 코드
네트워크 스트림에서 주로 쓰이는 방법이다.
1
2
3
4
5
6
7
8
9
10 |
static final int BYTE_SIZE=1024;
int bytesRead=0;
int bytesToRead=BYTE_SIZE;
byte[] input=new byte[bytesToRead];
while(bytesRead<bytesToRead){
int result=in.read(input,bytesRead,bytesToRead-bytesRead);
if(result==-1){ break; }
bytesRead+=result;
} |
대기없이 inputStream이 한번에 읽을 수 있는 최소한의 byte수만큼만 읽기
조심해서 써야한다. available()같은 경우 stream의 끝에 이를 경우 0을 반환하기 때문에 이렇게 쓰이기 보단 stream이 남아 있는지 여부를 판단하고
없을 경우 stream을 사용할 수 있게 비워주는 식의 코드를 짜야하는 경우 사용하는 것이 좋다.
1
2
3 |
int bytesToRead=in.available();
byte[] input=new byte[bytesToRead];
in.read(input,0,bytesToRead); |
'Programing > java' 카테고리의 다른 글
간단한 랜덤함수 사용법 (0) | 2015.04.29 |
---|---|
java Byte Order 바꾸기 : Little Endian (0) | 2015.01.31 |
java Mashalling과 Serialization의 차이 (0) | 2015.01.31 |
Java Serializable : 자바 직렬화 (0) | 2015.01.31 |
thread이야기_02.run()과 start()의 차이 (0) | 2014.11.23 |