InputStream提供的是字节流的读取,而非文本读取,用Reader读取出来的是char数组或者String ,使用InputStream读取出来的是byte数组。
Reader类及其子类提供的字符流的读取char,inputStream及其子类提供字节流的读取byte,所以 FileReader类是将文件按字符流的方式读取,FileInputStream则按字节流的方式读取文件;InputStreamReader可以将读如stream转换成字符流方式,是reader和stream之间的桥梁。
1 String –> Inputstream
1 2 3 | public InputSteam getInputStreamFromString(String str){ InputSteam in=new ByteArrayInputStream(str.getBytes()); } |
2 InputStream –> String
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 | public static String convertStreamToString(InputStream is) { StringBuilder sb = new StringBuilder(); String line = null; try { BufferedReader reader = new BufferedReader(new InputStreamReader(is)); while ((line = reader.readLine()) != null) { sb.append(line); } } catch (IOException e) { e.printStackTrace(); } finally { try { is.close(); } catch (IOException e) { e.printStackTrace(); } } return sb.toString(); } |