Programming/기본 (Baisc)
[JAVA][자바] Nio 이용해서 IO Read & Write (이어쓰기)
YH.Dream
2023. 1. 14. 23:44
1. 개요
1) 클라이어트 단에서 파일 업로드 시 Chunk화 하여 서버에 CPU 부하를 낮추기 위해 구현한다.
2) 차이점
가. AS-IS java.io 클래스의 경우 하드웨어가 아닌 JAVA → JVM → 하드웨어 → 디스크
나. TO-BE java.nio 클래스의 경우 JAVA → 하드웨어 → 디스크
으로 작성하다보니, 성능면에서 CPU가 안정적이고 부하가 존재하지 않아 매우 효율이 좋다.
2. 처리
// 존재하면 이어쓰기
OutputStream fileChannel = null;
Path path = Paths.get(newFile.getAbsolutePath());
try {
fileChannel = Files.newOutputStream(path, StandardOpenOption.CREATE, StandardOpenOption.APPEND);
log.info("InputStream save Proc");
int bufferSz = 1024 * 1024 * 10;
log.warn("InputStream Proc -1 ");
String[] array = new String(item.getInputStream().readAllBytes()).split(",");
ByteBuffer byteBuffer = ByteBuffer.allocate(array.length);
Arrays.stream(array).
forEach(itemData -> {
byteBuffer.put((byte) Integer.parseUnsignedInt(itemData));
});
log.warn("InputStream Proc -2 ");
fileChannel.write(byteBuffer.array());
log.warn("InputStream Proc -3 ");
} catch (IOException e) {
log.error("{} -- saveUploadFile", errorUtil.traceLog(e));
} finally {
IOUtils.closeQuietly(fileChannel);
try {
item.delete();
} catch (Exception e) {
}
}