Java中读取字节流并按指定编码转换成字符串的步骤
Java中读取字节流并按指定编码转换成字符串的方法
该方法中使用一个无限循环,从字节流中读取字节,存放到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, 0, 1024); // 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 ""; } }