IO流【带有缓冲区的字节输入、输出流;字符输入、输出流 转换流】

news2024/10/5 19:10:16

day35

学习注意事项

  1. 按照流的发展历史去学习
  2. 注意流与流之间的继承关系
  3. 举一反三

IO流

继day36

字节流继承图

字节流继承图

字节流

应用场景:操作二进制数据(音频、视频、图片)

abstract class InputStream – 字节输入流的基类(抽象类)

abstract class OutputStream – 字节输出流的基类(抽象类)

class FileInputStream extends InputStream – 文件字节输入流

class FileOutputStream extends OutputStream – 文件字节输出流

class FilterInputStream extends InputStream – 过滤器字节输入流

class FilterOutputStream extends OutputStream – 过滤器字节输出流

class BufferedInputStream extends FilterInputStream – 带缓冲区的字节输入流

class BufferedOutputStream extends FilterOutputStream – 带缓冲区的字节输出流

默认缓冲区大小:8192字节

3.带缓冲区的字节输出流

利用 带缓冲区的字节输出流 向文件写入数据

1)不处理异常的方式

2)文件存在的情况

3)文件不存在的情况

经验:所有的输出流,文件不存在的情况都会创建文件

public class Test01 {
	public static void main(String[] args) throws IOException {
		
		//1.创建流对象
		BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream("io.txt"));
		
		//2.写入数据
		bos.write("123abc".getBytes());
		
		//3.关闭资源
		bos.close();	
	}
}

4)在文件末尾追加内容

经验:在文件末尾追加考虑基础流的构造方法

public class Test02 {
	public static void main(String[] args) throws IOException {
		
		//1.创建流对象
		BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream("io.txt",true));
		
		//2.写入数据
		bos.write("123abc".getBytes());
		
		//3.关闭资源
		bos.close();
	}
}

5)处理异常的方式

写入数据也要抛异常

	public static void main(String[] args){
        
		BufferedOutputStream bos = null;
		try {
			//1.创建流对象
			bos = new BufferedOutputStream(new FileOutputStream("io.txt",true));
			//2.写入数据
			bos.write("123abc".getBytes());
			
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			//3.关闭资源
			if(bos != null){
				try {
					bos.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}	
	}
深入 带缓冲区的字节输出流

字节输出流对象调用write()【父类的write方法,但子类重写了】
理解: 将数据写入到字节缓冲数组中,提高效率
满了将数据写入到文件中
关闭时才将数据写入到文件中,即不管满没满都写入文件

public class Test04 {
	public static void main(String[] args) throws IOException{
		
//		FileOutputStream fos = new FileOutputStream("io.txt");
//		//写几次,就和硬盘交互几次  -- 6次(内存与硬盘交互的次数)
//		fos.write("1".getBytes());
//		fos.write("2".getBytes());
//		fos.write("3".getBytes());
//		fos.write("a".getBytes());
//		fos.write("b".getBytes());
//		fos.write("c".getBytes());
//		fos.close();
		
//		BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream("io.txt"));
//		//将数据写入到字节缓冲数组中 -- 1次(内存与硬盘交互的次数)
//		bos.write("1".getBytes());
//		bos.write("2".getBytes());
//		bos.write("3".getBytes());
//		bos.write("a".getBytes());
//		bos.write("b".getBytes());
//		bos.write("c".getBytes());
//		//关闭时才将数据写入到文件中
//		bos.close();
		
		//默认缓冲区 -- 8192个字节(8*1024)
		//BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream("io.txt"));
		
		//自定义缓冲区大小 -- 2048个字节
//		BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream("io.txt"), 2048);
	}
}
手撕BufferedOutputStream底层源码
public class FilterOutputStream extends OutputStream {
    
	protected OutputStream out;//0x001
    
    //out - 0x001
    public FilterOutputStream(OutputStream out) {
        this.out = out;
    }
    
    //b - [65]
    public void write(byte[] b) throws IOException {
        this.write(b, 0, b.length);
    }
    
    @SuppressWarnings("try")
    public void close() throws IOException {
        try (OutputStream ostream = out) {
            flush();
        }
    }
}
public class BufferedOutputStream extends FilterOutputStream {
    //缓冲区数组
    protected byte[] buf;//new byte[8192]
    //缓冲区存放数据的个数
    protected int count;//1
    
    //out - 0x001
    public BufferedOutputStream(OutputStream out) {
        this(out, 8192);
    }
    
    //out - 0x001
    //size - 8192
    public BufferedOutputStream(OutputStream out, int size) {
        super(out);
        if (size <= 0) {
            throw new IllegalArgumentException("Buffer size <= 0");
        }
        buf = new byte[size];
    }
    
    //b - [65]
    //off - 0
    //len - 1
    public synchronized void write(byte b[], int off, int len) throws IOException {
        //判断现在需要写出的数据长度是否大于缓冲区数组
        if (len >= buf.length) {//1 >= 8192
            //将缓冲区数组里的数据写入到文件,将缓冲区清空
            flushBuffer();
            //将线程需要写出的数据写入到文件
            out.write(b, off, len);
            return;
        }
        
        //判断现在需要写出的数据长度 超过了缓冲区剩余的存储长度
        if (len > buf.length - count) {//1 > 8192-0
            //将缓冲区数组里的数据写入到文件,将缓冲区清空
            flushBuffer();
        }
        //将数据写入到缓冲区数组里
        System.arraycopy(b, off, buf, count, len);
        //更新缓冲区数组数据个数
        count += len;
    }
    
    private void flushBuffer() throws IOException {
        //count > 0说明缓冲区数组里有数据
        if (count > 0) {
            super.out.write(buf, 0, count);//调用的是FileOutputSteam的write()
            count = 0;//缓冲区清空
        }
    }
    
    public synchronized void flush() throws IOException {
        //将缓冲区数组里的数据写入到文件,将缓冲区清空
        flushBuffer();
        super.out.flush();//调用的是FileOutputSteam的close() -- 关流
    }
}
FileOutputStream fos = new FileOutputStream("io.txt");//0x001
BufferedOutputStream bos = new BufferedOutputStream(fos);

bos.write("1".getBytes());
bos.write("2".getBytes());
bos.write("3".getBytes());
bos.write("a".getBytes());
bos.write("b".getBytes());
bos.write("c".getBytes());

bos.close();

4.带缓冲区的字节输入流

利用 带有缓冲区的字节输入流 读取文件里的数据
  1. 不处理异常

  2. 文件存在

  3. 文件不存在

经验:所有输入流,当文件不存在都会报错

public class Test05 {
	public static void main(String[] args) throws IOException {
		
		//1.创建流对象 (默认缓冲区大小:8192字节)
		//BufferedInputStream bis = new BufferedInputStream(new FileInputStream("io.txt"));
		
		//1.创建流对象 (自定义缓冲区大小:2048字节)
		BufferedInputStream bis = new BufferedInputStream(new FileInputStream("io.txt"),2048);
		
		//2.读取数据 
		byte[] bs = new byte[1024];
		int len;
		while((len = bis.read(bs)) != -1){
			System.out.println(new String(bs, 0, len));
		}
		
		//3.关闭资源
		bis.close();
	}
}
  1. 处理异常
	public static void main(String[] args) {
		
		BufferedInputStream bis = null;
		try {
			//1.创建流对象 (默认缓冲区大小:8192字节)
			bis = new BufferedInputStream(new FileInputStream("io.txt"));
			
			//2.读取数据 
			byte[] bs = new byte[1024];
			int len;
			while((len = bis.read(bs)) != -1){
				System.out.println(new String(bs, 0, len));
			}
			
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			//3.关闭资源
			if(bis != null){
				try {
					bis.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
	}

拷贝文件

利用 带有缓冲区的字节输入、输出流

思路:读取源文件,写入目标文件

public class Copy {
	public static void main(String[] args) throws IOException {
		
		BufferedInputStream bis = new BufferedInputStream(new FileInputStream("奇男子.mp4"));
		BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream("copy.mp4"));
		
		byte[] bs = new byte[1024];
		int len;
		while((len = bis.read(bs)) != -1){
			bos.write(bs, 0, len);
		}
		
		bis.close();
		bos.close();
	}
}

字符流

应用场景:操作纯文本数据

注意:字符流 = 字节流+编译器

编译器:可以识别中文字符和非中文字符,非中文字符获取1个字节(一个字节=一个字符),编译器会根据编码格式获取中文字符对应的字节数(GBK获取两个字节,UTF-8获取三个字节)

abstract class Reader – 字符输入流的基类(抽象类)

abstract class Writer – 字符输出流的基类(抽象类)

class InputStreamReader extends Reader – 字符输入转换流

class OutputStreamWriter extends Writer – 字符输出转换流

特点:将字节流转换为字符流,字符转换流是字节流和字符流的桥梁

class FileReader extends InputStreamReader – 文件字符输入流

class FileWriter extends OutputStreamWriter – 文件字符输出流

利用 字符输出转换流 向文件写入数据

  1. 不处理异常

  2. 文件存在

  3. 文件不存在

经验:所有的输出流,当文件不存在时都会创建文件

public class Test01 {
	public static void main(String[] args) throws IOException {
		
		//1.创建流对象(将文件字节输出流 转换为 字符输出转换流)
		OutputStreamWriter osw = new OutputStreamWriter(new FileOutputStream("io.txt"));
		
		//2.写入数据
		//osw.write(97);//写入码值
		
		//char[] cs = {'1','2','3','a','b','c','我','爱','你'};
		//osw.write(cs);//写入字符数组
		//osw.write(cs, 3, 4);//写入字符数组,偏移量,写入长度
		
		//osw.write("123abc我爱你");//字符串
		osw.write("123abc我爱你", 3, 4);//写入字符串,偏移量,写入长度
		
		//3.关闭资源
		osw.close();	
	}
}
  1. 文件末尾追加
    经验:考虑基础流的构造方法
public class Test02 {
	public static void main(String[] args) throws IOException {
		
		//1.创建流对象(将文件字节输出流 转换为 字符输出转换流)
		OutputStreamWriter osw = new OutputStreamWriter(new FileOutputStream("io.txt",true));
		
		//2.写入数据
		osw.write("123abc我爱你");
		
		//3.关闭资源
		osw.close();	
	}
}
  1. 处理异常
	public static void main(String[] args) {
		
		OutputStreamWriter osw = null;
		try {
			//1.创建流对象(将文件字节输出流 转换为 字符输出转换流)
			osw = new OutputStreamWriter(new FileOutputStream("io.txt",true),"UTF-8");
			
			//2.写入数据
			osw.write("123abc我爱你");
			
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			//3.关闭资源
			if(osw != null){
				try {
					osw.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
	}

利用 字符输入转换流 读取文件里的数据

  1. 不处理异常

  2. 文件存在

  3. 文件不存在

经验:所有的输入流,在文件不存在时都会报错

public class Test04 {
	public static void main(String[] args) throws IOException {
		
		//1.创建流对象
		InputStreamReader isr = new InputStreamReader(new FileInputStream("io.txt"));
		
		//2.读取数据
		//read() -- 读取字符,如果读取到文件末尾则返回-1
		int read = isr.read();
		System.out.println((char)read);
		read = isr.read();
		System.out.println((char)read);
		read = isr.read();
		System.out.println((char)read);
		read = isr.read();
		System.out.println((char)read);
		read = isr.read();
		System.out.println((char)read);
		read = isr.read();
		System.out.println((char)read);
		read = isr.read();
		System.out.println((char)read);
		read = isr.read();
		System.out.println((char)read);
		read = isr.read();
		System.out.println((char)read);
		read = isr.read();
		System.out.println(read);
		
		//3.关闭资源
		isr.close();
		
	}
}

减少冗余代码,但还是一个字节一个字节的读取数据

//while循环读取		
	//2.读取数据
    int read;
    while((read = isr.read()) != -1){
        System.out.println((char)read);
    }

加快读取

//指定长度读取
	//2.读取数据
	//isr.read(cs):读入cs数组长度的字符,将字符数据存入到数组中,并返回读取到的有效字节数,如果读取到文件末尾,则返回-1
	char[] cs = new char[1024];
	int len;
	while((len = isr.read(cs)) != -1){
		System.out.println(new String(cs, 0, len));
	}
  1. 处理异常

注意:使用字符转换流最好加上编码格式!

	public static void main(String[] args){
		
		InputStreamReader isr = null;
		try {
			//1.创建流对象
			isr = new InputStreamReader(new FileInputStream("io.txt"),"UTF-8");
			
			//2.读取数据
			//isr.read(cs):读入cs数组长度的字符,将字符数据存入到数组中,并返回读取到的有效字节数,如果读取到文件末尾,则返回-1
			char[] cs = new char[1024];
			int len;
			while((len = isr.read(cs)) != -1){
				System.out.println(new String(cs, 0, len));
			}
			
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			//3.关闭资源
			if(isr != null){
				try {
					isr.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
	}

拷贝文件

利用 字符输入、输出流 转换流

思路:读取源文件,写入目标文件

public class Copy {

	public static void main(String[] args) throws UnsupportedEncodingException, IOException {
		
		InputStreamReader isr = new InputStreamReader(new FileInputStream("小说.txt"), "GBK");
		OutputStreamWriter osw = new OutputStreamWriter(new FileOutputStream("copy.txt"), "GBK");
		
		char[] cs = new char[1024];
		int len;
		while((len = isr.read(cs)) != -1){
			osw.write(cs, 0, len);
		}
		
		isr.close();
		osw.close();
	}
}

总结:

1.BufferedInputStream 和 BufferedOutputStream
理解底层
理解缓冲区是如何提高效率

2.InputStreamReader 和 OutputStreamWriter
理解转换流(字节流 -> 字符流)

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/1574446.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

1、认识MySQL存储引擎吗?

目录 1、MySQL存储引擎有哪些&#xff1f; 2、默认的存储引擎是哪个&#xff1f; 3、InnoDB和MyISAM有什么区别吗&#xff1f; 3.1、关于事务 3.2、关于行级锁 3.3、关于外键支持 3.4、关于是否支持MVCC 3.5、关于数据安全恢复 3.6、关于索引 3.7、关于性能 4、如何…

项目经理想提升,可不止PMP这一个证书!

软考 系统集成项目管理工程师 信息系统项目管理师 中高项知识体系 软考价值&#xff1a; 软考的价值体现在多个方面&#xff1a; 在评职称方面&#xff0c;软考可以为个人提供北京工作居住证、一线城市积分落户等方面的支持&#xff0c;有利于个人在工作和生活中的稳定和发…

Java Netty个人对个人私聊demo

一、demo要求 1&#xff09;编写一个Netty个人对个人聊天系统&#xff0c;实现服务器端和客户端之间的数据简单通讯&#xff08;非阻塞&#xff09; 2&#xff09;实现单人对单人聊 3&#xff09;服务器端&#xff1a;可以监测用户上线&#xff0c;离线&#xff0c;并实现消…

【新手上路】C#联合Halcon第一个demo搭建

前言 学习Halcon目的是能够利用C#封装成一个视觉的上位机应用配合机器人或者过程控制来提高生产的效率&#xff0c;尤其是在检测外观和定位方面的应用。现在我们就来搭建第一个demo。让他们能够跑起来&#xff01; Halcon方面 打开Halcon软件&#xff0c;然后先随便写一个代…

ADW310 导轨式单相无线计量仪表-安科瑞黄安南

ADW310 无线计量仪表主要用于计量低压网络的有功电能&#xff0c;具有体积小、精度高、功能丰富等优点&#xff0c;并且可 选通讯方式多&#xff0c;可支持 RS485 通讯和 Lora、4G 等无线通讯方式&#xff0c;增加了外置互感器的电流采样模式&#xff0c;从而方便 用户在不同场…

uniapp使用npm命令引入font-awesome图标库最新版本

uniapp使用npm命令引入font-awesome图标库最新版本 图标库网址&#xff1a;https://fontawesome.com/search?qtools&or 命令行&#xff1a; 引入 npm i fortawesome/fontawesome-free 查看版本 npm list fortawesome在main.js文件中&#xff1a; import fortawesome/fo…

想在小红书写出数据分析类的爆文?带你分析爆文的写作思路

一、小红书运营分析背景介绍 在如今社交媒体的浪潮中&#xff0c;小红书、抖音、知乎等平台的流量如同滚滚长江&#xff0c;吸引了无数公司和品牌前来淘金。对于想要推广公司的产品和主营业务而言&#xff0c;如何在这些平台上脱颖而出&#xff0c;成为了一大难题。 数据分析&a…

Java文件流操作

一、文件创建和删除 public static void main(String[] args) throws IOException {File file new File("..\\hello-world.txt");//..表示在上机目录下创建hello-world.txtSystem.out.println(file.getPath());//返回当前相对路径System.out.println(file.getCanoni…

小型案例(acl,nat,dns,dhcp,静态路由)

实验目录&#xff1a;内网互通&#xff0c;pc不可以访问外网&#xff0c;server2可以通过外网访问&#xff08;nat技术&#xff09;&#xff0c;pc2&#xff0c;和pc3可以访问外网 拓扑图如下 配置信息如图&#xff0c;pc1~3 和server2 对应vlan分别是10&#xff0c;20&#…

Matlab 修改图例顺序

对于使用 .m 文件绘制的图片&#xff0c;可以修改程序中图例的顺序来改变图片的图例。如果图片所对应的 .fig 文件已经存在&#xff0c;而且不便修改源程序&#xff0c;则可以通过如下方式来修改图例&#xff1a; step 1: 打开fig文件&#xff0c;然后点击绘图浏览器 step 2&…

Qt实现无边框圆角窗口

我们在使用QDialog的时候许多场景下都不需要默认的标题栏&#xff0c;这时候我们需要设置他的标志位。 this->setWindowFlags(Qt::FramelessWindowHint);由于现代的窗口风格&#xff0c;我们一般会设置窗口为圆角边框的样式&#xff0c;我们可以使用qss的方式来进行设置。 …

WebAPI(一)之DOM操作元素属性和定时器

webAPI之DOM操作元素属性和定时器 介绍概念DOM 树DOM 节点document 获取DOM对象操作元素内容操作元素属性常用属性修改控制样式属性操作表单元素属性自定义属性 间歇函数今日单词 了解 DOM 的结构并掌握其基本的操作&#xff0c;体验 DOM 的在开发中的作用 知道 ECMAScript 与 …

鱼骨图功能实现

dom: <div class="module-content"><div class="title"><span>[</span><p>鱼骨图</p><span>]</span></div><div class="line-mian"></div><div :ref="module + i&q…

Francek Chen 的128天创作纪念日

目录 Francek Chen 的128天创作纪念日机缘收获日常成就憧憬 Francek Chen 的128天创作纪念日 Francek Chen 的个人主页 机缘 不知不觉的加入CSDN已有两年时间了&#xff0c;最初我第一次接触CSDN技术社区是在2022年4月的时候&#xff0c;通过学长给我们推荐了几个IT社区平台&a…

Redis数据库——主从、哨兵、群集

目录 前言 一、主从复制 1.基本原理 2.作用 3.流程 4.搭建主动复制 4.1环境准备 4.2修改主服务器配置 4.3从服务器配置&#xff08;Slave1和Slave2&#xff09; 4.4查看主从复制信息 4.5验证主从复制 二、哨兵模式——Sentinel 1.定义 2.原理 3.作用 4.组成 5.…

数字逻辑分析仪初体验

为啥会用到这玩意儿&#xff0c;要从一个荒诞的需求开始。想在市面上找一款特别低空飞行的监控&#xff0c;而且不想它一直开着监控&#xff0c;最好是我在外面远程指挥它起飞&#xff0c;飞去厨房&#xff0c;飞去洗手间&#xff0c;甚至飞去阳台&#xff0c;查看水龙头情况啊…

【力扣白嫖日记】1435.制作会话柱状图

前言 练习sql语句&#xff0c;所有题目来自于力扣&#xff08;https://leetcode.cn/problemset/database/&#xff09;的免费数据库练习题。 今日题目&#xff1a; 1435.制作会话柱状图 表&#xff1a;Sessions 列名类型session_idintdurationint session_id 是该表主键,d…

技术驱动下的同城O2O发展:跑腿配送APP开发教学

在同城生活服务领域&#xff0c;跑腿配送APP的出现与发展&#xff0c;为人们的日常生活提供了极大的便利。今天&#xff0c;小编将着重为大家讲解技术驱动下的同城O2O发展&#xff0c;并从跑腿配送APP的开发角度进行教学和解析。 一、同城O2O发展概述 在同城O2O模式中&#x…

摆动序列(力扣376)

文章目录 题目前知题解一、思路二、解题方法三、Code 总结 题目 Problem: 376. 摆动序列 如果连续数字之间的差严格地在正数和负数之间交替&#xff0c;则数字序列称为 摆动序列 。第一个差&#xff08;如果存在的话&#xff09;可能是正数或负数。仅有一个元素或者含两个不等元…

《web应用技术》第二次课后练习

练习目的&#xff1a; 1、form表单值的获取 2、mysql数据库及表的建立&#xff08;参见视频&#xff09; 3、maven项目的建立&#xff08;参见视频&#xff09; 4、使用jdbc进行数据库的增删改查操作。&#xff08;参见源代码&#xff09; 具体如下&#xff1a; 1、继续理…