不知道我應該如何做到這一點。任何幫助,將不勝感激將InputStream(圖片)轉換爲ByteArrayInputStream
12
A
回答
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);
相關問題
- 1. 強制轉換一個ByteArrayInputStream來的InputStream
- 2. 將ZipOutputStream轉換爲ByteArrayInputStream
- 3. 將ByteArrayInputStream轉換爲xml文件
- 4. 將Jetty Buffer轉換爲InputStream
- 5. Java:將InputStream轉換爲OutputStream
- 6. 將inputStream轉換爲FileInputStream?
- 7. 將InputStream轉換爲BufferedReader
- 8. 將InputStream轉換爲FileInputStream
- 9. 將InputStream轉換爲MediaPlayer
- 10. 將InputStreamReader轉換爲InputStream
- 11. 將UTF字符串轉換爲InputStream
- 12. 如何將InputStream轉換爲FileStream?
- 13. 在java中將InputStream轉換爲MappedByteBuffer?
- 14. java將inputStream轉換爲base64字符串
- 15. 如何將InputStream轉換爲Source?
- 16. 將InputStream轉換爲字符串(telnet)
- 17. 在Java中將InputStream轉換爲FileItem
- 18. 將SAX ContentHandler字符(..)轉換爲InputStream
- 19. 將inputStream從ZipFile轉換爲字符串
- 20. 如何將byte []轉換爲InputStream?
- 21. 如何將對象轉換爲InputStream
- 22. 如何將InputStream轉換爲DataHandler?
- 23. 如何將javax.xml.transform.Source轉換爲InputStream?
- 24. 如何將JSP InputStream轉換爲ServletResponse?
- 25. NullPointerException:解析XML,從ByteArrayInputStream創建InputStream(string.getBytes())
- 26. InputStream和ByteArrayInputStream有什麼區別?
- 27. 將ByteArrayInputStream的內容轉換爲字符串
- 28. 將圖片轉換爲二進制BASE64
- 29. 試圖將活動轉換爲片段
- 30. 將對齊段落轉換爲圖片
由於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
你到底在做什麼,你將不會使用'javax.imageio'類的圖像? – Powerlord 2010-08-16 18:59:03
上傳到Amazon S3 ...我正在使用的Java庫需要ByteArrayInputStream用於所有基於非字符串的數據 – user398371 2010-08-17 15:45:12