File 与 IO 流

File 概述

​ File 类中有很多关于文件/目录的操作,基本能包含自己想要的全部功能,所以在使用的时候要查 api

IO 概述

  • 按操作数据单位不同分为:字节流和字符流

  • 按数据流的流向不同分为:输入流和输出流

  • 按流的角色不同分为:节点流和处理流

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

    Java 的 IO 流共涉及 40 多个类,都是从这四个抽象基类派生出来的。

节点流:直接是程序和文件直接的流

处理流:作用在节点流之上,对节点流做优化或添加新的功能。
在这里插入图片描述

使用 IO 流

读操作

@Test
public void test4() {   //最好使用 try-catch-finally 的方法,否则如果出现异常流不会被自动关闭
    //1.创建 File 对象
    File file1 = new File("helloworld.txt");
    FileReader fr = null;
    try {
        //2.创建流
        fr = new FileReader(file1);
        char[] cbuf = new char[5];
        int len;
        //3.把流中的内容读取到的缓冲区中
        while((len = fr.read(cbuf)) != -1) {    
            for(int i = 0; i < len; i++) {
                System.out.print(cbuf[i]);
            }
        }
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        //4.关闭流
        if(fr != null) {
            try {
                fr.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

写操作

public void test5() {
    FileWriter fw = null;
    try {
        //1.创建流
        fw = new FileWriter("helloworld2.txt");
        //2.写入
        fw.write("hello, file");
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        if(fw != null) {
            try {
                //3.关闭流
                fw.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

缓冲流演示

public void test5() {
    BufferedReader br = null;
    BufferedWriter bw = null;
    try {
        //创建缓冲流,它是对节点流的包装
        br = new BufferedReader(new FileReader("helloworld.txt"));
        bw = new BufferedWriter(new FileWriter("helloworld2.txt"));

        char[] cbuf = new char[5];
        int len;
        while((len = br.read(cbuf)) != -1) {
            bw.write(cbuf, 0, len);
        }
        bw.flush(); //刷新缓冲区,这里的缓冲区是指 BufferedWriter 的缓冲区,而不是 cbuf
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        //关闭流
        if(br != null) {
            try {
                br.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        if(bw != null) {
            try {
                bw.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值