IO流

1.概念:IO流本质就是一套进行数据传输的机制,

  根据数据传输的方向可分为:   输入流---数据往内存中传输      输出流---数据从内存中往外流出

  根据数据传输的方式可分为:字符流     字节流

  IO流四大基本流都是抽象类

 

 输出流输入流
字符流WriterReader
字节流OutputStreamInputStream

2.缓冲流

   BufferedReader---提供了一个缓冲区

(读文件时会先将内容存入缓冲区),在构建的时候需要传入一个reader对象,真正读取数据时依靠的是这个对象

 public static void main(String[] args) throws Exception {

                                      FileReader reader=new FileReader("D:\\a.txt");
                                      BufferedReader br=new BufferedReader(reader);
                                       String str;

                                //readLine方法表示读取一行数据,读到最后一行会返回null
                                    while((str=br.readLine())!=null){
                                   System.out.println(str)
                                         }

                                          br.close();
                                   }

   BufferedWriter---提供了一个更大的缓冲区

(因为好多输出流本身存在缓冲区,所以此流用的少)

 public static void main(String[] args) throws Exception {
       BufferedWriter writer=new BufferedWriter(new FileWriter("D:\\a.txt"));
               //向文件中写数据
                writer.write("abc");
                 //关流
                writer.close();
    }

3.FileOutputStream---文件字节输出流

   //字节输出流向文件中写数据
    public static void main(String[] args) throws IOException {
        FileOutputStream out=new FileOutputStream("D:\\a.txt");
        //需要将字符转化为字节数组
        out.write("abc".getBytes());
        //写入成功,说明字节输出流没有缓冲区,不需要flush
        out.close();
    }

   FileInputStrem---文件字节输入流

   //字节输入流读取数据
    public static void main(String[] args) throws IOException {
        FileInputStream fileInputStream=new FileInputStream("D:\\a.txt");
        //定义字节数组作为缓冲区
        byte[]b=new byte[1024];
        int a;

       //将数据读到数组中
        while((a=fileInputStream.read(b))!=-1){
            System.out.println(new String(b,0,a));
        }

        fileInputStream.close()
    }

   FileWriter----文件字符输出流

 //字符输出流向文件中写数据
    public static void main(String[] args) throws IOException {
        FileWriter writer=new FileWriter("D:\\a.txt");
  //先将数据写到缓冲区中,缓冲区未满,程序就已经结束,导致数据死在缓冲区
        writer.write("123");
        //将缓冲区中的数据冲到文件中
        writer.flush();
        writer.close();
    }

   FileReader---文件字符输入流

 //文件字节输入流读取数据
   public static void main(String[] args) throws IOException {
        FileReader reader=new FileReader("D:\\a.txt");
        char[]c=new char[1024];
        int a;
        while((a=reader.read(c))!=-1){
            System.out.println(new String(c,0,a));
        }
        reader.close();
    }

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值