-
Java로 InputStream 에서 Byte Array, ByteBuffer 변환
방법1
public void conv1() throws IOException { InputStream is = new ByteArrayInputStream(new byte[] { 0, 1, 2, 3, 4, 5, 6 }); byte[] targetArray = new byte[is.available()]; is.read(targetArray); }
방법2
public void cnv2() throws IOException { InputStream is = new ByteArrayInputStream(new byte[] { 0, 1, 2, 3, 4, 5, 6 }); // not really known ByteArrayOutputStream buffer = new ByteArrayOutputStream(); int nRead; byte[] data = new byte[4]; //Starting with Java 9: while ((nRead = is.readNBytes(data, 0, data.length)) != 0) { //read()는 최대로 읽고, readNBytes()는 요청된 만큼만 읽는다. while ((nRead = is.read(data, 0, data.length)) != -1) { buffer.write(data, 0, nRead); } buffer.flush(); byte[] targetArray = buffer.toByteArray(); }
방법3
public void cnv3() throws IOException { InputStream is = new ByteArrayInputStream(new byte[] { 0, 1, 2 }); byte[] data = is.readAllBytes(); }
'Java' 카테고리의 다른 글
반복문 for 흐름 Ex (0) 2022.11.30 getPath(), getAbsolutePath(), getCanonicalPath() (0) 2022.08.08 RxJava subscribeOn, observeOn (0) 2022.08.07 Callable, Runnable 차이 (0) 2022.08.07 Thread IO UI 혼용 문제 증상 (0) 2022.08.07 RxJava HttpUrlConnection (0) 2022.08.07 RxJava 스케쥴러(Scheduler) 종류 (0) 2022.08.07 HttpURLConnection (0) 2022.08.07