溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務條款》

android中怎么實現String與InputStream相互轉換

發布時間:2021-07-12 11:33:12 來源:億速云 閱讀:344 作者:Leah 欄目:編程語言

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相互轉換的方法了嗎?如果還想學到更多技能或想了解更多相關內容,歡迎關注億速云行業資訊頻道,感謝各位的閱讀!

向AI問一下細節

免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。

AI

亚洲午夜精品一区二区_中文无码日韩欧免_久久香蕉精品视频_欧美主播一区二区三区美女