2010-08-16 80 views
12

不知道我應該如何做到這一點。任何幫助,將不勝感激將InputStream(圖片)轉換爲ByteArrayInputStream

+0

由於ByteArrayInputStream的是從字節[] http://stackoverflow.com/questions/2163644/in-java-how-can-i-convert-an-inputstream-into-a-byte-array-構造字節http://stackoverflow.com/questions/1264709/convert-inputstream-to-byte-in-java – h3xStream 2010-08-16 18:22:03

+0

你到底在做什麼,你將不會使用'javax.imageio'類的圖像? – Powerlord 2010-08-16 18:59:03

+0

上傳到Amazon S3 ...我正在使用的Java庫需要ByteArrayInputStream用於所有基於非字符串的數據 – user398371 2010-08-17 15:45:12

回答

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 2010-08-16 18:35:58

+0

歡迎您:) – naikus 2010-08-16 18:52:40

1

或者先將其轉換爲一個字節數組,然後到一個ByteArrayInputStream。

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); 
相關問題