java中inputstream_java中InputStream String
Java 中獲取輸入流時,有時候須要將輸入流轉成String,以便獲取當中的內容 ,以下總結一下 InputStream 轉成String 的方式
方法1:
public?String?convertStreamToString(InputStream?is)?{
BufferedReader?reader?=?new?BufferedReader(new?InputStreamReader(is));
StringBuilder?sb?=?new?StringBuilder();
String?line?=?null;
try?{
while?((line?=?reader.readLine())?!=?null)?{
sb.append(line?+?"/n");
}
}?catch?(IOException?e)?{
e.printStackTrace();
}?finally?{
try?{
is.close();
}?catch?(IOException?e)?{
e.printStackTrace();
}
}
return?sb.toString();
}
方法2:
public?? String?? inputStream2String?? (InputStream?? in)?? throws?? IOException?? {
StringBuffer?? out?? =?? new?? StringBuffer();
byte[]?? b?? =?? new?? byte[4096];
for?? (int?? n;?? (n?? =?? in.read(b))?? !=?? -1;)?? {
out.append(new?? String(b,?? 0,?? n));
}
return?? out.toString();
}
方法3:
public?? static?? String?? inputStream2String(InputStream?? is)?? throws?? IOException{
ByteArrayOutputStream?? baos?? =?? new?? ByteArrayOutputStream();
int?? i=-1;
while((i=is.read())!=-1){
baos.write(i);
}
return?? baos.toString();
}
String 轉成 InputStream
String str = "String與InputStream相互轉換";
InputStream ? in_nocode?? = ? new ? ByteArrayInputStream(str.getBytes());
InputStream ? in_withcode?? = ? new ? ByteArrayInputStream(str.getBytes("UTF-8"));
總結
以上是生活随笔為你收集整理的java中inputstream_java中InputStream String的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: java servlet https_j
- 下一篇: java 字节序列_java – 这个线