IO流【带有缓冲区的字节输入、输出流;字符输入、输出流 转换流】-程序员宅基地

技术标签: 学习  java  

day35

学习注意事项

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

IO流

继day34

字节流继承图

字节流继承图

字节流

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

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字节 - new byte[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
理解转换流(字节流 -> 字符流)

版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://blog.csdn.net/gangain/article/details/137439077

智能推荐

874计算机科学基础综合,2018年四川大学874计算机科学专业基础综合之计算机操作系统考研仿真模拟五套题...-程序员宅基地

文章浏览阅读1.1k次。一、选择题1. 串行接口是指( )。A. 接口与系统总线之间串行传送,接口与I/0设备之间串行传送B. 接口与系统总线之间串行传送,接口与1/0设备之间并行传送C. 接口与系统总线之间并行传送,接口与I/0设备之间串行传送D. 接口与系统总线之间并行传送,接口与I/0设备之间并行传送【答案】C2. 最容易造成很多小碎片的可变分区分配算法是( )。A. 首次适应算法B. 最佳适应算法..._874 计算机科学专业基础综合题型

XShell连接失败:Could not connect to '192.168.191.128' (port 22): Connection failed._could not connect to '192.168.17.128' (port 22): c-程序员宅基地

文章浏览阅读9.7k次,点赞5次,收藏15次。连接xshell失败,报错如下图,怎么解决呢。1、通过ps -e|grep ssh命令判断是否安装ssh服务2、如果只有客户端安装了,服务器没有安装,则需要安装ssh服务器,命令:apt-get install openssh-server3、安装成功之后,启动ssh服务,命令:/etc/init.d/ssh start4、通过ps -e|grep ssh命令再次判断是否正确启动..._could not connect to '192.168.17.128' (port 22): connection failed.

杰理之KeyPage【篇】_杰理 空白芯片 烧入key文件-程序员宅基地

文章浏览阅读209次。00000000_杰理 空白芯片 烧入key文件

一文读懂ChatGPT,满足你对chatGPT的好奇心_引发对chatgpt兴趣的表述-程序员宅基地

文章浏览阅读475次。2023年初,“ChatGPT”一词在社交媒体上引起了热议,人们纷纷探讨它的本质和对社会的影响。就连央视新闻也对此进行了报道。作为新传专业的前沿人士,我们当然不能忽视这一热点。本文将全面解析ChatGPT,打开“技术黑箱”,探讨它对新闻与传播领域的影响。_引发对chatgpt兴趣的表述

中文字符频率统计python_用Python数据分析方法进行汉字声调频率统计分析-程序员宅基地

文章浏览阅读259次。用Python数据分析方法进行汉字声调频率统计分析木合塔尔·沙地克;布合力齐姑丽·瓦斯力【期刊名称】《电脑知识与技术》【年(卷),期】2017(013)035【摘要】该文首先用Python程序,自动获取基本汉字字符集中的所有汉字,然后用汉字拼音转换工具pypinyin把所有汉字转换成拼音,最后根据所有汉字的拼音声调,统计并可视化拼音声调的占比.【总页数】2页(13-14)【关键词】数据分析;数据可..._汉字声调频率统计

linux输出信息调试信息重定向-程序员宅基地

文章浏览阅读64次。最近在做一个android系统移植的项目,所使用的开发板com1是调试串口,就是说会有uboot和kernel的调试信息打印在com1上(ttySAC0)。因为后期要使用ttySAC0作为上层应用通信串口,所以要把所有的调试信息都给去掉。参考网上的几篇文章,自己做了如下修改,终于把调试信息重定向到ttySAC1上了,在这做下记录。参考文章有:http://blog.csdn.net/longt..._嵌入式rootfs 输出重定向到/dev/console

随便推点

uniapp 引入iconfont图标库彩色symbol教程_uniapp symbol图标-程序员宅基地

文章浏览阅读1.2k次,点赞4次,收藏12次。1,先去iconfont登录,然后选择图标加入购物车 2,点击又上角车车添加进入项目我的项目中就会出现选择的图标 3,点击下载至本地,然后解压文件夹,然后切换到uniapp打开终端运行注:要保证自己电脑有安装node(没有安装node可以去官网下载Node.js 中文网)npm i -g iconfont-tools(mac用户失败的话在前面加个sudo,password就是自己的开机密码吧)4,终端切换到上面解压的文件夹里面,运行iconfont-tools 这些可以默认也可以自己命名(我是自己命名的_uniapp symbol图标

C、C++ 对于char*和char[]的理解_c++ char*-程序员宅基地

文章浏览阅读1.2w次,点赞25次,收藏192次。char*和char[]都是指针,指向第一个字符所在的地址,但char*是常量的指针,char[]是指针的常量_c++ char*

Sublime Text2 使用教程-程序员宅基地

文章浏览阅读930次。代码编辑器或者文本编辑器,对于程序员来说,就像剑与战士一样,谁都想拥有一把可以随心驾驭且锋利无比的宝剑,而每一位程序员,同样会去追求最适合自己的强大、灵活的编辑器,相信你和我一样,都不会例外。我用过的编辑器不少,真不少~ 但却没有哪款让我特别心仪的,直到我遇到了 Sublime Text 2 !如果说“神器”是我能给予一款软件最高的评价,那么我很乐意为它封上这么一个称号。它小巧绿色且速度非

对10个整数进行按照从小到大的顺序排序用选择法和冒泡排序_对十个数进行大小排序java-程序员宅基地

文章浏览阅读4.1k次。一、选择法这是每一个数出来跟后面所有的进行比较。2.冒泡排序法,是两个相邻的进行对比。_对十个数进行大小排序java

物联网开发笔记——使用网络调试助手连接阿里云物联网平台(基于MQTT协议)_网络调试助手连接阿里云连不上-程序员宅基地

文章浏览阅读2.9k次。物联网开发笔记——使用网络调试助手连接阿里云物联网平台(基于MQTT协议)其实作者本意是使用4G模块来实现与阿里云物联网平台的连接过程,但是由于自己用的4G模块自身的限制,使得阿里云连接总是无法建立,已经联系客服返厂检修了,于是我在此使用网络调试助手来演示如何与阿里云物联网平台建立连接。一.准备工作1.MQTT协议说明文档(3.1.1版本)2.网络调试助手(可使用域名与服务器建立连接)PS:与阿里云建立连解释,最好使用域名来完成连接过程,而不是使用IP号。这里我跟阿里云的售后工程师咨询过,表示对应_网络调试助手连接阿里云连不上

<<<零基础C++速成>>>_无c语言基础c++期末速成-程序员宅基地

文章浏览阅读544次,点赞5次,收藏6次。运算符与表达式任何高级程序设计语言中,表达式都是最基本的组成部分,可以说C++中的大部分语句都是由表达式构成的。_无c语言基础c++期末速成