1.(StringBuffer+InputStreamReader+BufferedReader ),不推薦使用,BufferedReader在readLine() 時會在讀取到換行符時直接返回,然後讀取下一行,會丟失換行符(what fk is that?)。
public String inputStreamString (InputStream in) throws IOException {
String tempLine="";
StringBuffer resultBuffer = new StringBuffer();
InputStreamReader inputStreamReader = new InputStreamReader(in);
BufferedReader reader = new BufferedReader(inputStreamReader);
while ((tempLine = reader.readLine()) != null) {
resultBuffer.append(tempLine);
}
return resultBuffer.toString();
}
複製程式碼
2.(ByteArrayOutputStream)推薦使用
public String intputStreamString2(InputStream inputStream){
ByteArrayOutputStream baos = new ByteArrayOutputStream();
int i=-1;
try {
while((i=inputStream.read())!=-1){
baos.write(i);
}
return baos.toString();
} catch (IOException e) {
e.printStackTrace();
}
return "";
}
複製程式碼