여러 InputStream을 String화 한다든지, 다른 Output으로 저장을 한다든지등으로 byte[]화 하는 경우가 많다.
이런 경우 다음과 같이 Util성 static method를 만들어 사용하면 많은 도움이 된다.
private byte[] getBytes(InputStream is) {
BufferedInputStream bis = new BufferedInputStream(is);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
int bytesRead = 0;
byte[] buffer = new byte[10000];
try {
while ((bytesRead = bis.read(buffer)) >= 0) {
baos.write(buffer, 0, bytesRead);
}
bis.close();
} catch (Throwable e) {
return null;
} finally {
try {
if (is != null)
is.close();
} catch (Exception ex) {
}
}
return baos.toByteArray();
}
apache common io를 사용하는 경우 아래와 같이 사용한다.
InputStream is;
// ...
byte[] bytes = org.apache.commons.io.IOUtils.toByteArray(is);
개인적으로 코드는 dependency가 있는건 별로 좋지 않다. ^^;
반응형
'Language > Java' 카테고리의 다른 글
Java에서 MacAddress 가져오기 (0) | 2019.08.19 |
---|---|
코딩 표기법 정리 (0) | 2019.08.17 |
StringBuffer와 StringBuilder의 차이점 (0) | 2019.08.17 |