Java
업무 중에 알게 된 inputStream, outputStream
정ㅇr
2021. 12. 1. 16:57
728x90
@RequestMapping(value = "/pricePolicy/impressionExcelFile", method = RequestMethod.GET)
public ResponseEntity<byte[]> impressionExcelFile(HttpServletRequest httpRequest) {
Long pricePolicyId = Long.parseLong(httpRequest.getParameter("pricePolicyId"));
Long priceId = Long.parseLong(httpRequest.getParameter("priceId"));
Price price = priceService.selectPriceFilePath(pricePolicyId, priceId);
InputStream inputStream;
ByteArrayOutputStream byteArrayOutputStream;
try {
inputStream = new FileInputStream(price.getPriceFilePath() + price.getPriceFileName());
logger.debug("PriceController.inputStream : " + inputStream);
byteArrayOutputStream = new ByteArrayOutputStream();
byte[] buffer = new byte[512];
int count = inputStream.read(buffer);
logger.debug("PriceController.count : " + count);
while (count > 0) {
byteArrayOutputStream.write(buffer,0,count);
count = inputStream.read(buffer); // 여기에 다시 선언한 이유가 뭐지? ㅇㅣ 코드 없으면 OutOfMemory 에러 남
}
HttpHeaders header = new HttpHeaders();
header.setContentType(MediaType.APPLICATION_OCTET_STREAM);
header.setContentDispositionFormData("attachment", "InputImpression_" + pricePolicyId + ".xls");
return new ResponseEntity<byte[]>(byteArrayOutputStream.toByteArray(), header, HttpStatus.OK);
} catch(IOException e) {
throw new IBCException(IBCError.CANNOT_RUN_REQUEST, "파일을 생성하는데 실패했습니다.");
}
}
}
여기서 왜 바이트 크기를 512로 정해놓았는지 갑자기 궁금해졌다.
https://unix.stackexchange.com/questions/365949/what-does-the-size-in-512-byte-blocks-mean
이 사이트에서의 답변에 따르면,

간단하게 말하자면, 데이터를 저장할 때 컴퓨터의 하드디스크 메모리 관리를 효율적으로 하기 위해서 512라는 숫자로 바이트 크기를 정해서 낭비하지 않게 한다는 내용이다.
확실히 CS 지식이 많이 없다보니까 메모리, 자원관리 이런 부분이 나오면 생소하다. 공부가 더 필요하다.
아래는 inputStream, outStream 등 자바 stream에 관해서 잘 설명해놓은 블로그 주소다.
반응형