java IO流学习笔记

本文详细介绍了Java中的I/O流,包括流的概念、分类,如按方向、单位和功能划分,重点讨论了字节流和字符流,涵盖了文件流、缓冲流、对象流、序列化与反序列化、编码方式、PrintWriter、转换流以及File类的使用,如递归遍历和删除文件夹。
摘要由CSDN通过智能技术生成

I/O 框架

1 流的概念

内存与存储设备之间传输数据的通道
在这里插入图片描述

2 流的分类

2.1 按方向【重点】

  • 输入流:将<存储设备>中的内容读到<内存>中
  • 输出流:将<内存>中的内容写到<存储设备>中

2.2 按单位

  • 字节流:以字节为单位,可以读写所有数据
  • 字符流:以字符为单位,只能读写文本数据

2.3 按功能

  • 节点流:具有实际传输数据的读写功能
  • 过滤流:在节点流的基础之上增强功能

3 字节流

下面两个为字节流的父类(抽象类)

//InputStream 字节输入流
public int read(){
   }
public int read(byte[] b){
   }
public int read(byte[] b, int off, int len){
   }

// OutputStream 字节输出流
public void write(int n){
   }
public void write(byte[] b){
   }
public void write(byte[] b, int off, int len){
   }

3.1 文件字节流

文件输入流

psvm(String[] args) throws Exception{
   
    // 1 创建FileInputStream 并指定文件路径
    FileInputStream fis = new FileInputStream("d:\\abc.txt");
    // 2 读取文件
    // fis.read();
    // 2.1单字节读取
    int data = 0;
    while((data = fis.read()) != -1){
   
        sout((char)data);
    }
    // 2.2 一次读取多个字节
    byte[] buf = new byte[3]; // 大小为3的缓存区
    int count = fis.read(buf); // 一次读3个
    sout(new String(buf));
    sout(count);
    int count2 = fis.read(buf); // 再读3个
    sout(new String(buf));
    sout(count2);

    // 上述优化后
    int count = 0;
    while((count = fis.read(buf)) != -1){
   
        sout(new String(buf, 0, count));
    }

    // 3 关闭
    fis.close();
}

文件输出流

psvm(String[] args) throws Exception{
   
    // 1 创建文件字节输出流
    FileOutputStream fos = new FileOutputStream("路径", true);// true表示不覆盖 接着写 
    // 2 写入文件
    fos.write(97);
    fos.write('a');
    // String string = "hello world";
    fos.write(string.getByte());
    // 3 关闭
    fos.close();
} 

3.2 图片复制案例

// 1 创建流
// 1.1 文件字节输入流
FileInputStream fis = new FileInputStream("路径");
// 1.2 文件字节输出流
FileInputStream fos = new FileOutpuStream("路径");
// 2 边读边写
byte[] buf = new byte[1024];
int count = 0;
while((count = fis.read(buf)) != -1){
   
    fos.write(buf, 0, count);
}
// 3 关闭
fis.close();
fos.close();

3.3 字节缓冲流

缓冲流:BufferedInputStream / BufferedOutputStream

  • 提高IO效率,减少访问磁盘次数
  • 数据存储在缓冲区中,flush是将缓冲区的内容写入文件中,也可以直接close
// 使用字节缓冲流 读取 文件
psvm(String[] args) throws Exception{
   
    // 1 创建BufferedInputStream
    FileInputStream fis = new FileInputStream("路径");
    BufferedInputStream bis = new BufferedInputStream(fis); //缓冲区默认大小:8192=8kb
    // 2 读取
    int data = 0;
    while((data = bis
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值