android中怎么實現String與InputStream相互轉換,相信很多沒有經驗的人對此束手無策,為此本文總結了問題出現的原因和解決方法,通過這篇文章希望你能解決這個問題。
一:純手戳代碼:
1.String to InputStream
String str = “String與InputStream相互轉換”;
//str.getBytes()方法是得到一個操作系統默認的編碼格式的字節數組,見
http://blog.itpub.net/28932681/viewspace-2286124/
InputStream in_nocode = new ByteArrayInputStream(str.getBytes());
InputStream in_withcode = new ByteArrayInputStream(str.getBytes(“UTF-8”));
2.InputStream to 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"); //這里的“/n”一定要加上,原因見http://blog.itpub.net/28932681/viewspace-2286126/ } } 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 len=-1;
byte[] buffer=new byte[1024];
while((len=is.read(buffer))!=-1){
baos.write(buffer, 0, len);
}
is.close();
return baos.toString();
//return new String(baos.toByteArray());
}
二:通過第三方jar包實現,推薦一個jar包,用來轉換InputStream到String,代碼示例如下:
1 // 引入apache的io包
2 import org.apache.commons.io.IOUtils;
3
4 InputStream in = con.getInputStream();
5 String result = IOUtils.toString(in, “UTF-8”);
看完上述內容,你們掌握android中怎么實現String與InputStream相互轉換的方法了嗎?如果還想學到更多技能或想了解更多相關內容,歡迎關注億速云行業資訊頻道,感謝各位的閱讀!
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。