Java IO流


1 流的分类

数据单位
字节流:非文本,图片、视频等
字符流:文本

流向
输入流
输出流

角色
节点流:直接作用在文件上
处理流:在已有基础上包了一层流,例如要加快流的速度而做的流

抽象基类字节流字符流
输入流InputStreamReader
输出流OutputStreamWriter

在这里插入图片描述

2 示例代码

1.FileReader读入

        // 1、实例化File类对象,指明要操作的文件
        //     读的时候file一定要存在,不然会报FileNotFoundException异常
        // 2、提供据具体的流
        // 3、数据的读入
        // 4、流的关闭
    @Test
    public void test4() {
        FileReader fr = null;
        try {
            // 1、实例化File类对象,指明要操作的文件
            // 读的时候file一定要存在,不然会报FileNotFoundException异常
            File file = new File("C:\\Users\\22370\\Desktop\\spring\\start\\src\\main\\java\\com\\ll\\aaaa.txt");
            // 2、提供据具体的流
            fr =new FileReader(file);
            // 3、数据的读入
            int data = fr.read();
            while (data !=-1){
                System.out.println((char) data);
                data=fr.read();
            }
        }catch (IOException e){
                e.printStackTrace();
        }finally {
            // 4、流的关闭
            try {
                if(null!=fr){
                    fr.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

fr.read();一个个的读字符,效率比较低下,使用char[] buf。

            // 3、数据的读入
            char[] buf=new char[5];
            // fr.read()返回每次读入的数组中的个数
            int len = fr.read(buf);
            while (len !=-1){
                // 方式一
//                for (int i = 0; i < len; i++) {
//                    System.out.print(buf[i]);
//                }
                // 方式二
                String s=new String(buf,0,len);
                System.out.print(s);
                len=fr.read(buf);
            }

2.缓冲流实现文件复制

        File file1 = new File("C:\\Users\\22370\\Desktop\\spring\\start\\src\\main\\java\\com\\ll\\3.jpg");
        File file2 = new File("C:\\Users\\22370\\Desktop\\spring\\start\\src\\main\\java\\com\\ll\\4.jpg");
        FileInputStream is = null;
        FileOutputStream fo=null;
        BufferedInputStream bis=null;
        BufferedOutputStream bos=null;
        try {
            is = new FileInputStream(file1);
            fo = new FileOutputStream(file2);

            bis = new BufferedInputStream(is);
            bos = new BufferedOutputStream(fo);

            byte[] bytes=new byte[10];
            int len = 0;
            while ((len=bis.read(bytes))!=-1){
                bos.write(bytes,0,len);
            }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值