該方法中使用一個無限循環,從字節流中讀取字節,存放到byte數組中,每次讀取1024個字節(一般都是這個設置),由于每次讀取的字節數量不一定夠1024個(比如最后一次的讀取就可能不夠),所以我們要記錄每次實際讀到的字節數,然后將實際讀取到的字節按指定的編碼方式轉換成字符串。
private String inputStreamToString(InputStream is, String encoding) {
try {
byte[] b = new byte[1024];
String res = "";
if (is == null) {
return "";
}
int bytesRead = 0;
while (true) {
bytesRead = is.read(b, 0, 1024); // return final read bytes counts
if (bytesRead == -1) {// end of InputStream
return res;
}
res += new String(b, 0, bytesRead, encoding); // convert to string using bytes
}
} catch (Exception e) {
e.printStackTrace();
System.out.print("Exception: " + e);
return "";
}
}
try {
byte[] b = new byte[1024];
String res = "";
if (is == null) {
return "";
}
int bytesRead = 0;
while (true) {
bytesRead = is.read(b, 0, 1024); // return final read bytes counts
if (bytesRead == -1) {// end of InputStream
return res;
}
res += new String(b, 0, bytesRead, encoding); // convert to string using bytes
}
} catch (Exception e) {
e.printStackTrace();
System.out.print("Exception: " + e);
return "";
}
}
-------------------------------------------------------------
生活就像打牌,不是要抓一手好牌,而是要盡力打好一手爛牌。