java读取输入流

时间:2020-12-30 07:40:51

java读取输入流两种

    private static byte[] readStream(InputStream in){
if(in==null){
return null;
} byte[] buffer = null; try { int availableLength = 0;
while(availableLength==0){
availableLength = in.available();//可获取的字节流长度 if(availableLength==0&&in.read()==-1){//防止读取流返回为空造成死循环
break;
}
} buffer = new byte[availableLength]; int readCount = 0;
while(readCount<availableLength){
readCount += in.read(buffer, readCount, availableLength-readCount);
} } catch (IOException e) {
e.printStackTrace();
} finally{
if(in!=null){
try {
in.close();
in = null;
} catch (IOException e) {
e.printStackTrace();
}
} } return buffer;
} public static byte[] readStream1(InputStream in) { byte[] b = null;
ByteArrayOutputStream outSteam = null;
try {
byte[] buffer = new byte[1024 * 4];
outSteam = new ByteArrayOutputStream(); int len = -1;
while ((len = in.read(buffer)) != -1) {
outSteam.write(buffer, 0, len);
} b = outSteam.toByteArray();
} catch (IOException e) {
e.printStackTrace();
} finally{
try {
if(outSteam!=null){
outSteam.close();
outSteam = null;
}
if(in!=null){
in.close();
in = null;
}
} catch (IOException e) {
e.printStackTrace();
}
}
return b;
}