黑马程序员———IO转换流笔记

转换流的由来: 字符流与字节流之间的桥梁 方便了字符流与字节流之间的操作
转换流的应用: 字节流中的数据都是字符时,转成字符流操作更高效。
转换流:

InputStreamReader:字节到字符的桥梁,解码。

OutputStreamWriter:字符到字节的桥梁,编码。

InputStreamReader是字节流通向字符流的桥梁。
示例1:
  1. 1.        import java.io.BufferedReader;

  2. 2.        import java.io.IOException;

  3. 3.        import java.io.InputStream;

  4. 4.        import java.io.InputStreamReader;

  5. 05.

  6. 6.        public class TransStreamDemo{

  7. 07.

  8. 8.        public static void main(String[] args) throws IOException {

  9. 9.        //字节流

  10. 10.        InputStream in = System.in;

  11. 11.

  12. 12.        //将字节转成字符的桥梁,转换流

  13. 13.        InputStreamReader isr = new InputStreamReader(in);

  14. 14.

  15. 15.        //对字符流进行高效装饰,缓冲区

  16. 16.        BufferedReader bufr = new BufferedReader(isr);

  17. 17.

  18. 18.        String line = null;

  19. 19.

  20. 20.        //读取到了字符串数据

  21. 21.        while((line = bufr.readLine()) != null){

  22. 22.        if("over" .equals(line))

  23. 23.        break;

  24. 24.        System.out.println(line.toUpperCase());

  25. 25.        }

  26. 26.        }

  27. 27.        }
复制代码



使用字节流读取一个中文字符需要读取两次,因为一个中文字符由两个字节组成,而使用字符流只需读取一次。
System.out的类型是PrintStream,属于OutputStream类别。

OutputStreamReader是字符流通向字节流的桥梁。
示例2:
1.        import java.io.BufferedReader;

2.        import java.io.BufferedWriter;

3.        import java.io.IOException;

4.        import java.io.InputStream;

5.        import java.io.InputStreamReader;

6.        import java.io.OutputStream;

7.        import java.io.OutputStreamWriter;

08.

9.        public class TransStreamDemo{

10.

11.        public static void main(String[] args) throws IOException {

12.

13.        InputStream in = System.in;

14.

15.        InputStreamReader isr = new InputStreamReader(in);

16.

17.        //字符流

18.        BufferedReader bufr = new BufferedReader(isr);

19.

20.        //字节流,字节数据

21.        OutputStream out = System.out;

22.

23.        //数据到了osw,目的地out控制台

24.        OutputStreamWriter osw = new OutputStreamWriter(out);

25.

26.        BufferedWriter bufw = new BufferedWriter(osw);

27.

28.        String line = null;

29.

30.        while((line = bufr.readLine()) != null){

31.        if("over" .equals(line))

32.        break;

33.

34.        //将字符数据用缓冲区对象将数据写入缓冲区,目的地是osw

35.        bufw.write(line.toUpperCase());

36.        bufw.newLine();

37.        //osw.write(line.toUpperCase() + "\r\n");可以替代上面两行代码

38.        bufw.flush();

39.        }

40.        }

41.        }


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值