posts - 262,  comments - 221,  trackbacks - 0

该方法中使用一个无限循环,从字节流中读取字节,存放到byte数组中,每次读取1024个字节(一般都是这个设置),由于每次读取的字节数量不一定够1024个(比如最后一次的读取就可能不够),所以我们要记录每次实际读到的字节数,然后将实际读取到的字节按指定的编码方式转换成字符串。

private String inputStreamToString(InputStream is, String encoding) {
    try {
        
byte[] b = new byte[1024];
         String res 
= "";
         
if (is == null) {
                
return "";
         }
         
         
int bytesRead = 0;
        
while (true) {
             bytesRead 
= is.read(b, 01024); // return final read bytes counts
             
if (bytesRead == -1) {// end of InputStream
                    return res;
             }
             res +=
 new String(b, 0, bytesRead, encoding); // convert to string using bytes
          }
      } 
catch (Exception e) {
            e.printStackTrace();
            System.out.print(
"Exception: " + e);
            
return "";
      }
}


-------------------------------------------------------------
生活就像打牌,不是要抓一手好牌,而是要尽力打好一手烂牌。
posted on 2008-08-06 09:59 Paul Lin 阅读(17286) 评论(2)  编辑  收藏 所属分类: J2SE


FeedBack:
# re: Java中读取字节流并按指定编码转换成字符串的方法
2008-12-16 12:50 | kmh
inputstream 的 read 方法是阻塞的,不知道次方法楼主已经实现了吗?  回复  更多评论
  
# re: Java中读取字节流并按指定编码转换成字符串的方法[未登录]
2008-12-16 20:50 | Paul Lin
@kmh

InputStream的read方法是阻塞的,所以在实际的应用环境中我的做法是将其放在一个Thread或Runnable implement的类中,由run()方法调用,这样其中一个线程在执行到read方法而导致阻塞时,不会影响其他线程。

不知你有没有更好的方法,欢迎探讨  回复  更多评论
  

只有注册用户登录后才能发表评论。


网站导航:
 
<2008年8月>
272829303112
3456789
10111213141516
17181920212223
24252627282930
31123456

常用链接

留言簿(21)

随笔分类

随笔档案

BlogJava热点博客

好友博客

搜索

  •  

最新评论

阅读排行榜

评论排行榜