file 從InputStream讀取byte[]示例
- public static byte[] getStreamBytes(InputStream is) throws Exception {
- ByteArrayOutputStream baos = new ByteArrayOutputStream();
- byte[] buffer = new byte[1024];
- int len = 0;
- while ((len = is.read(buffer)) != -1) {
- baos.write(buffer, 0, len);
- }
- byte[] b = baos.toByteArray();
- is.close();
- baos.close();
- return b;
- }
- default byte[] readFileBytes(InputStream is){
- byte[] data = null;
- try {
- if(is.available()==0){//嚴謹起見,一定要加上這個判斷,不要返回data[]長度為0的數組指針
- return data;
- }
- data = new byte[is.available()];
- is.read(data);
- is.close();
- return data;
- } catch (IOException e) {
- LogCore.BASE.error("readFileBytes, err", e);
- return data;
- }
- }
-
圖片上傳功能是我們web里面經常用到的,獲得的方式也有很多種,這里我用的是request.getInputStream()獲取文件流的方式。想要獲取文件流有兩種方式,附上代碼
12345678910int length = request.getContentLength();//獲取請求參數長度。
byte[] bytes = new byte[length];//定義數組,長度為請求參數的長度
DataInputStream dis = new DataInputStream(request.getInputStream);//獲取請求內容,轉成數據輸入流
int readcount = 0;//定義輸入流讀取數
while(readcount < length){
int aa= dis.read(bytes,readcount,length); //讀取輸入流,放入bytes數組,返回每次讀取的數量
readcount = aa + readcount; //下一次的讀取開始從readcount開始
}
//讀完之后bytes就是輸入流的字節數組,將其轉為字符串就能看到
String bb = new String(bytes,"UTF-8");
上面這種是利用讀取輸入流的方式,也可以用寫入字節輸入流的方式獲取,就不需要獲取請求長度了
123456789DataInputStream dis = new DataInputStream(request.getInputStream());
ByteArrayOutputStream baot = new ByteArrayOutputStream();
byte[] bytes = new byte[1024]; //定義一個數組 用來讀取
int n = 0;//每次讀取輸入流的量
while((n=dis.read(bytes))!=-1){
baot.write(bytes); //將讀取的字節流寫入字節輸出流
}
byte[] outbyte = boat.toByteArray();//將字節輸出流轉為自己數組。
String bb = new String(outbyte,"UTF-8");
-