android中怎么實(shí)現(xiàn)String與InputStream相互轉(zhuǎn)換,相信很多沒有經(jīng)驗(yàn)的人對此束手無策,為此本文總結(jié)了問題出現(xiàn)的原因和解決方法,通過這篇文章希望你能解決這個問題。

創(chuàng)新互聯(lián)公司:2013年開創(chuàng)至今為各行業(yè)開拓出企業(yè)自己的“網(wǎng)站建設(shè)”服務(wù),為超過千家公司企業(yè)提供了專業(yè)的做網(wǎng)站、成都網(wǎng)站建設(shè)、網(wǎng)頁設(shè)計(jì)和網(wǎng)站推廣服務(wù), 按需網(wǎng)站設(shè)計(jì)由設(shè)計(jì)師親自精心設(shè)計(jì),設(shè)計(jì)的效果完全按照客戶的要求,并適當(dāng)?shù)奶岢龊侠淼慕ㄗh,擁有的視覺效果,策劃師分析客戶的同行競爭對手,根據(jù)客戶的實(shí)際情況給出合理的網(wǎng)站構(gòu)架,制作客戶同行業(yè)具有領(lǐng)先地位的。
一:純手戳代碼:
1.String to InputStream
String str = “String與InputStream相互轉(zhuǎn)換”;
//str.getBytes()方法是得到一個操作系統(tǒng)默認(rèn)的編碼格式的字節(jié)數(shù)組,見
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());
}
二:通過第三方j(luò)ar包實(shí)現(xiàn),推薦一個jar包,用來轉(zhuǎn)換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”);
看完上述內(nèi)容,你們掌握android中怎么實(shí)現(xiàn)String與InputStream相互轉(zhuǎn)換的方法了嗎?如果還想學(xué)到更多技能或想了解更多相關(guān)內(nèi)容,歡迎關(guān)注創(chuàng)新互聯(lián)行業(yè)資訊頻道,感謝各位的閱讀!
文章標(biāo)題:android中怎么實(shí)現(xiàn)String與InputStream相互轉(zhuǎn)換
網(wǎng)站地址:http://chinadenli.net/article38/jpsesp.html
成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供微信公眾號、外貿(mào)建站、做網(wǎng)站、品牌網(wǎng)站設(shè)計(jì)、品牌網(wǎng)站制作、網(wǎng)站制作
聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請盡快告知,我們將會在第一時間刪除。文章觀點(diǎn)不代表本網(wǎng)站立場,如需處理請聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時需注明來源: 創(chuàng)新互聯(lián)