2010-08-16 3 views
12

어떻게해야하나요? 어떤 도움을 주시면 감사하겠습니다.InputStream (Image)을 ByteArrayInputStream으로 변환하십시오.

+0

는 http://stackoverflow.com/questions/2163644/in-java-how-can-i-convert-an-inputstream-into-a-byte-array- [] 바이트로 구성되어 byte http://stackoverflow.com/questions/1264709/convert-inputstream-to-byte-in-java – h3xStream

+0

'javax.imageio' 클래스를 사용하지 않는 이미지로 정확히 무엇을하고 있습니까? – Powerlord

+0

Amazon S3에 업로드 중 ... Java 라이브러리에서 문자열 기반이 아닌 모든 데이터에 대해 ByteArrayInputStream이 필요합니다. – user398371

답변

18

입력 스트림에서 읽고 ByteArrayOutputStream에 쓰고 그 다음 toByteArray()을 호출하여 바이트 배열을 가져옵니다.

바이트 배열을 중심으로 ByteArrayInputStream을 작성하여 읽습니다. 첫째

import java.io.*; 

public class Test { 


     public static void main(String[] arg) throws Throwable { 
      File f = new File(arg[0]); 
      InputStream in = new FileInputStream(f); 

      byte[] buff = new byte[8000]; 

      int bytesRead = 0; 

      ByteArrayOutputStream bao = new ByteArrayOutputStream(); 

      while((bytesRead = in.read(buff)) != -1) { 
      bao.write(buff, 0, bytesRead); 
      } 

      byte[] data = bao.toByteArray(); 

      ByteArrayInputStream bin = new ByteArrayInputStream(data); 
      System.out.println(bin.available()); 
     } 
} 
+0

거의 다 왔어요! 예를 들어 주셔서 감사합니다. IO의 진정한 마스터! – user398371

+0

당신은 환영합니다 :) – naikus

1

또는 다음이 InputStream에, 바이트 배열로 변환 :

여기에 빠른 테스트입니다. 이 InputStream 이후

File f = new File(arg[0]); 
InputStream in = new FileInputStream(f); 
// convert the inpustream to a byte array 
byte[] buf = null; 
try { 
    buf = new byte[in.available()]; 
    while (in.read(buf) != -1) { 
    } 
} catch (Exception e) { 
    System.out.println("Got exception while is -> bytearr conversion: " + e); 
} 
// now convert it to a bytearrayinputstream 
ByteArrayInputStream bin = new ByteArrayInputStream(buf);