Java IO流小结

看过好多遍了,老是忘,在这里巩固下

字节流、字符流的区别就不说了:

0101010101

*^#*&IGIUGI

InputStream就是01010101001——byte[]

Writer、Reader就是*^#*&IGIUGI——char[]

如何把字节流转化成字符流呢?

字节流:01010101001

我们需要按照一定的编码格式对字节流进行操作,把这些0和1转化成char

所以InputStreamReader就是来完成这件事的

但是InputStreamReader是一个字符一个字符读的,性能不好,所以需要再封装一层

BufferedReader。它是一行一行读的

接下来实战一下

先把字符转换成字节

String string = "安卓思丢diu";
byte[] bytes = string.getBytes("utf-8");

输出如下

    -27
    -82
    -119
    -27
    -115
    -109
    -26
    -128
    -99
    -28
    -72
    -94
    100
    105
    117
(暂时我只会这么转,好像没有字符流到字节流的办法)

再把上面得到的字节流转化成字符流

InputStream byteArrayInputStream = new ByteArrayInputStream(bytes);
InputStreamReader inputStreamReader = new InputStreamReader(byteArrayInputStream, "utf-8");
BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
String line;
while ((line = bufferedReader.readLine()) != null) {
    Log.i(TAG, line);
}

扩展下,输入流转输出流

InputStream byteArrayInputStream = new ByteArrayInputStream(bytes);
OutputStream outputStream = new ByteArrayOutputStream();
byte[] buffer = new byte[5];
int len;
while ((len = byteArrayInputStream.read(buffer)) != -1) {
    outputStream.write(buffer, 0, len);
}

最后,别忘了把前面的东西关关光啊!!不然要出事的啊!

xxxstream.close

flush需要调用吗?

可能需要。有些流的stream.close里默认实现了stream.flush,但是有些没有, 所以最好还是调用一下,否则有数据 丢失的可能。其作用是当缓冲 区未被填满的 时候,仍然强制刷新缓存区到 输出流中。

猜你喜欢

转载自blog.csdn.net/qq_36523667/article/details/81392562