이 예는 Java의 InputStream
및 OutputStream
을 사용하여 URL에서 이미지를 다운로드하는 방법을 보여줍니다. OutputStream.write()
메서드 사용이 다른 두 가지 코드 조각이 제공됩니다. 결과를 분석해 보겠습니다.
방법 1: write(byte[] b, int off, int len)
이 메서드는 바이트 배열의 일부를 출력 스트림에 씁니다. 코드는 입력 스트림에서 데이터를 청크(한 번에 1024바이트) 단위로 효율적으로 읽고 동일한 청크를 출력 스트림에 씁니다. 이것이 이미지와 같은 바이너리 데이터를 처리하는 정확하고 효율적인 방법입니다.
<code class="language-java">String val = "https://akcdn.detik.net.id/community/media/visual/2023/03/04/sholat-jenazah_169.jpeg"; URL url = new URL(val); InputStream in = new BufferedInputStream(url.openStream()); ByteArrayOutputStream out = new ByteArrayOutputStream(); byte[] buf = new byte[1024]; int n = 0; while (-1 != (n=in.read(buf))) { out.write(buf, 0, n); // Correctly writes the chunk of bytes } out.close(); in.close(); byte[] response = out.toByteArray(); FileOutputStream fos = new FileOutputStream("D:/my-image1.jpg"); fos.write(response); // Writes the complete byte array to the file fos.close();</code>
방법 2: write(int n)
이 방법은 출력 스트림에 단일 바이트를 씁니다. 잘못 코드는 in.read(buf)
의 반환 값(읽은 바이트 수를 나타냄)을 쓸 단일 바이트로 해석합니다. 이는 데이터 손상으로 이어집니다.
<code class="language-java">String val = "https://akcdn.detik.net.id/community/media/visual/2023/03/04/sholat-jenazah_169.jpeg"; URL url = new URL(val); InputStream in = new BufferedInputStream(url.openStream()); ByteArrayOutputStream out = new ByteArrayOutputStream(); int n = 0; while (-1 != (n=in.read(buf))) { out.write(n); // Incorrectly writes only a single byte, corrupting the image data } out.close(); in.close(); byte[] response = out.toByteArray(); FileOutputStream fos = new FileOutputStream("D:/my-image2.jpg"); fos.write(response); fos.close();</code>
결과 및 이미지 속성:
방법 1(my-image1.jpg
)을 사용하여 다운로드한 이미지는 예상 파일 크기로 올바르게 렌더링된 이미지가 됩니다. 방법 2(my-image2.jpg
)는 데이터 손상으로 인해 이미지가 깨지거나 부분적으로 렌더링되고 파일 크기가 더 작아질 수 있습니다. 제공된 이미지 파일 비교는 시각적으로나 파일 크기 측면에서 이러한 차이를 보여줍니다.
결론적으로 바이너리 데이터 스트림을 처리할 때는 항상 write(byte[] b, int off, int len)
메서드를 사용하여 데이터 무결성을 보장하고 손상을 방지하세요. write(int n)
메서드는 단일 바이트를 쓰는 데에만 적합하며 더 큰 데이터 청크를 처리하는 데는 부적합합니다.
위 내용은 Java ByteArrayOutputStream.write(int n)와 ByteArrayOutputStream.write(byte[] b, int off, int len)의 차이점의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!