Java 缓冲流、转换流

第一章 缓冲流

1.1 概述

缓冲流,也叫高效流,是对4个基本的 FileXxx 流的增强,所以也是4个流,按照数据类型分类:

字节缓冲流
BufferedInputStreamBufferedOutputStream

字符缓冲流
BufferedReader , BufferedWriter

缓冲流的基本原理,是在创建流对象时,会创建一个内置的默认大小的缓冲区数组,通过缓冲区读写,减少系统IO 次数,从而提高读写的效率

1.2 字节缓冲流

构造方法

  • public BufferedInputStream(InputStream in) :创建一个 新的缓冲输入流。
  • public BufferedOutputStream(OutputStream out) : 创建一个新的缓冲输出流。

使用步骤

  1. 创建FileOutputStream对象,构造方法中绑定要输出的目的地
  2. 创建BufferedOutputStream对象,构造方法中传递FileOutputStream对象
  3. 使用BufferedOutputStream对象中的方法write,把数据写入到内部缓冲区
  4. 使用BufferedOutputStream对象中的方法flush,把内部缓冲区中的数据刷新到文件中
  5. 释放资源(会先调用flush方法刷新数据,第四步可以省略)

使用步骤

  1. 创建FileInputStream对象,构造方法中绑定要输出的目的地
  2. 创建BufferedInputStream对象,构造方法中传递FileInputStream对象
  3. 使用BufferedInputStream对象中的方法read,把数据写入到内部缓冲区
  4. 释放资源

构造举例,代码如下:

// 创建字节缓冲输入流
BufferedInputStream bis = new BufferedInputStream(new FileInputStream("bis.txt"));
// 创建字节缓冲输出流
BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream("bos.txt"));

效率测试 :

一读一写

查询API,缓冲流读写方法与基本的流是一致的,我们通过复制大文件(375MB),测试它的效率。

  1. 基本流,代码如下:
public class BufferedDemo {
	public static void main(String[] args) throws FileNotFoundException {
		// 记录开始时间
		long start = System.currentTimeMillis();
		// 创建流对象
		try (
			FileInputStream fis = new FileInputStream("jdk9.exe");
			FileOutputStream fos = new FileOutputStream("copy.exe")
		){
			// 读写数据
			int b;
			while ((b = fis.read()) !=1) {
				fos.write(b);
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
		// 记录结束时间
		long end = System.currentTimeMillis();
		System.out.println("普通流复制时间:"+(end ‐ start)+" 毫秒");
	}
}
十几分钟过去了...
  1. 缓冲流,代码如下:
public class BufferedDemo {
	public static void main(String[] args) throws FileNotFoundException {
		// 记录开始时间
		long start = System.currentTimeMillis();
		// 创建流对象
		try (
			BufferedInputStream bis = new BufferedInputStream(new FileInputStream("jdk9.exe"));
			BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream("copy.exe"));
		){
		// 读写数据
			int b;
			while ((b = bis.read()) !=1) {
				bos.write(b);
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
		// 记录结束时间
		long end = System.currentTimeMillis();
		System.out.println("缓冲流复制时间:"+(end ‐ start)+" 毫秒");
	}
}
缓冲流复制时间:8016 毫秒

如何更快呢?
3. 使用数组的方式,代码如下:

public class BufferedDemo {
	public static void main(String[] args) throws FileNotFoundException {
		// 记录开始时间
		long start = System.currentTimeMillis();
		// 创建流对象
		try (
		BufferedInputStream bis = new BufferedInputStream(new FileInputStream("jdk9.exe"));
		BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream("copy.exe"));
	){
			// 读写数据
			int len;
			byte[] bytes = new byte[8*1024];
			while ((len = bis.read(bytes)) !=1) {
				bos.write(bytes, 0 , len);
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
		// 记录结束时间
		long end = System.currentTimeMillis();
		System.out.println("缓冲流使用数组复制时间:"+(end ‐ start)+" 毫秒");
	}
}
缓冲流使用数组复制时间:666 毫秒

1.3 字符缓冲流

构造方法 :

  • public BufferedReader(Reader in) :创建一个 新的缓冲输入流。
  • public BufferedWriter(Writer out) : 创建一个新的缓冲输出流。

构造举例,代码如下:

// 创建字符缓冲输入流
BufferedReader br = new BufferedReader(new FileReader("br.txt"));
// 创建字符缓冲输出流
BufferedWriter bw = new BufferedWriter(new FileWriter("bw.txt"));

特有方法:
字符缓冲流的基本方法与普通字符流调用方式一致,不再阐述,我们来看它们具备的特有方法。

  • BufferedReader:public String readLine() : 读一行文字。
  • BufferedWriter:public void newLine() : 写一行行分隔符,由系统属性定义符号。

readLine 方法演示,代码如下:

public class BufferedReaderDemo {
	public static void main(String[] args) throws IOException {
		// 创建流对象
		BufferedReader br = new BufferedReader(new FileReader("in.txt"));
		// 定义字符串,保存读取的一行文字
		String line = null;
		// 循环读取,读取到最后返回null
		while ((line = br.readLine())!=null) {
			System.out.print(line);
			System.out.println("‐‐‐‐‐‐");
		}
		// 释放资源
		br.close();
	}
}

newLine 方法演示,代码如下:

public class BufferedWriterDemo throws IOException {
	public static void main(String[] args) throws IOException {
		// 创建流对象
		BufferedWriter bw = new BufferedWriter(new FileWriter("out.txt"));
		// 写出数据
		bw.write("我是");
		// 写出换行
		bw.newLine();
		bw.write("程序");
		bw.newLine();
		bw.write("员");
		bw.newLine();
		// 释放资源
		bw.close();
	}
}
输出效果:
我是
程序
员

1.4 练习:文本排序

请将文本信息恢复顺序。

3.侍中、侍郎郭攸之、费祎、董允等,此皆良实,志虑忠纯,是以先帝简拔以遗陛下。愚以为宫中之事,事无大小,悉 以咨之,然后施行,必得裨补阙漏,有所广益。
8.愿陛下托臣以讨贼兴复之效,不效,则治臣之罪,以告先帝之灵。若无兴德之言,则责攸之、祎、允等之慢,以彰其 咎;陛下亦宜自谋,以咨诹善道,察纳雅言,深追先帝遗诏,臣不胜受恩感激。
4.将军向宠,性行淑均,晓畅军事,试用之于昔日,先帝称之曰能,是以众议举宠为督。愚以为营中之事,悉以咨之, 必能使行阵和睦,优劣得所。
2.宫中府中,俱为一体,陟罚臧否,不宜异同。若有作奸犯科及为忠善者,宜付有司论其刑赏,以昭陛下平明之理,不 宜偏私,使内外异法也。
1.先帝创业未半而中道崩殂,今天下三分,益州疲弊,此诚危急存亡之秋也。然侍卫之臣不懈于内,忠志之士忘身于外 者,盖追先帝之殊遇,欲报之于陛下也。诚宜开张圣听,以光先帝遗德,恢弘志士之气,不宜妄自菲薄,引喻失义,以 塞忠谏之路也。
9.今当远离,临表涕零,不知所言。
6.臣本布衣,躬耕于南阳,苟全性命于乱世,不求闻达于诸侯。先帝不以臣卑鄙,猥自枉屈,三顾臣于草庐之中,咨臣 以当世之事,由是感激,遂许先帝以驱驰。后值倾覆,受任于败军之际,奉命于危难之间,尔来二十有一年矣。
7.先帝知臣谨慎,故临崩寄臣以大事也。受命以来,夙夜忧叹,恐付托不效,以伤先帝之明,故五月渡泸,深入不毛。 今南方已定,兵甲已足,当奖率三军,北定中原,庶竭驽钝,攘除奸凶,兴复汉室,还于旧都。此臣所以报先帝而忠陛 下之职分也。至于斟酌损益,进尽忠言,则攸之、祎、允之任也。
5.亲贤臣,远小人,此先汉所以兴隆也;亲小人,远贤臣,此后汉所以倾颓也。先帝在时,每与臣论此事,未尝不叹息 痛恨于桓、灵也。侍中、尚书、长史、参军,此悉贞良死节之臣,愿陛下亲之信之,则汉室之隆,可计日而待也

案例分析 :

  1. 逐行读取文本信息。
  2. 解析文本信息到集合中。
  3. 遍历集合,按顺序,写出文本信息。
    java.lang.string.split
    split 方法,可以把字符串按照指定的分割符进行分割,然后返回字符串数组
    案例实现:
public class BufferedTest {
	public static void main(String[] args) throws IOException {
		// 创建map集合,保存文本数据,键为序号,值为文字
		HashMap<String, String> lineMap = new HashMap<>();
		
		// 创建流对象
		BufferedReader br = new BufferedReader(new FileReader("in.txt"));
		BufferedWriter bw = new BufferedWriter(new FileWriter("out.txt"));
		
		// 读取数据
		String line = null;
		while ((line = br.readLine())!=null) {
			// 解析文本
			String[] split = line.split("\\.");
			// 保存到集合
			lineMap.put(split[0],split[1]);
			}
			// 释放资源
			br.close();

		// 遍历map集合
		for (int i = 1; i <= lineMap.size(); i++) {
			String key = String.valueOf(i);
			// 获取map中文本
			String value = lineMap.get(key);
			// 写出拼接文本
			bw.write(key+"."+value);
			// 写出换行
			bw.newLine();
		}
		// 释放资源
		bw.close();
	}
}

第二章 转换流

2.1 字符编码和字符集

字符编码 :
计算机中储存的信息都是用二进制数表示的,而我们在屏幕上看到的数字、英文、标点符号、汉字等字符是二进制 数转换之后的结果。按照某种规则,将字符存储到计算机中,称为编码 。反之,将存储在计算机中的二进制数按照 某种规则解析显示出来,称为解码 。比如说,按照A规则存储,同样按照A规则解析,那么就能显示正确的文本f符 号。反之,按照A规则存储,再按照B规则解析,就会导致乱码现象。
字符编码 Character Encoding : 就是一套自然语言的字符与二进制数之间的对应规则。

字符集 :
字符集 Charset :也叫编码表。是一个系统支持的所有字符的集合,包括各国家文字、标点符号、图形符 号、数字等。

计算机要准确的存储和识别各种字符集符号,需要进行字符编码,一套字符集必然至少有一套字符编码。常见字符 集有ASCII字符集、GBK字符集、Unicode字符集等。
在这里插入图片描述
可见,当指定了编码,它所对应的字符集自然就指定了,所以编码才是我们最终要关心的。

2.2 编码引出的问题

在IDEA中,使用 FileReader 读取项目中的文本文件。由于IDEA的设置,都是默认的 UTF-8 编码,所以没有任何 问题。但是,当读取Windows系统中创建的文本文件时,由于Windows系统的默认是GBK编码,就会出现乱码。

2.3 InputStreamReader类

转换流 java.io.InputStreamReader ,是Reader的子类,是从字节流到字符流的桥梁。它读取字节,并使用指定 的字符集将其解码为字符。它的字符集可以由名称指定,也可以接受平台的默认字符集。

构造方法:

  • InputStreamReader(InputStream in) : 创建一个使用默认字符集的字符流。
  • InputStreamReader(InputStream in, String charsetName) :
    创建一个指定字符集的字符流。

构造举例,代码如下:

InputStreamReader isr = new InputStreamReader(new FileInputStream("in.txt"));
InputStreamReader isr2 = new InputStreamReader(new FileInputStream("in.txt") , "GBK");

指定编码读取:

public class ReaderDemo2 {
	public static void main(String[] args) throws IOException {
		// 定义文件路径,文件为gbk编码
		String FileName = "E:\\file_gbk.txt";
		// 创建流对象,默认UTF8编码
		InputStreamReader isr = new InputStreamReader(new FileInputStream(FileName));
		// 创建流对象,指定GBK编码
		InputStreamReader isr2 = new InputStreamReader(new FileInputStream(FileName) , "GBK");
		// 定义变量,保存字符
		int read;
		// 使用默认编码字符流读取,乱码
		while ((read = isr.read()) !=1) {
			System.out.print((char)read); // ��Һ�
			}
			isr.close();

		// 使用指定编码字符流读取,正常解析
		while ((read = isr2.read()) !=1) {
			System.out.print((char)read);// 大家好
		}
		isr2.close();
	}
}

2.4 OutputStreamWriter类

转换流 java.io.OutputStreamWriter ,是Writer的子类,是从字符流到字节流的桥梁。使用指定的字符集将字符 编码为字节。它的字符集可以由名称指定,也可以接受平台的默认字符集。

构造方法:

  • OutputStreamWriter(OutputStream in) : 创建一个使用默认字符集的字符流。

  • OutputStreamWriter(Output Stream in, String charsetName) :

    使用步骤:

    1. 创建OutputStreamWriter对象,构造方法中传递字节输出流和指定的变吗表名称
    2. 使用OutputStreamWriter对象中的方法write,把字符转换为字节存储缓存区中(编码)
    3. 使用OutputStreamWriter对象中的方法flush,把内存缓存区中的字节刷新到文件中(使用字节流写字节的过程)
    4. 释放资源
      构造举例,代码如下:

创建一个指定字符集的字符流:

OutputStreamWriter isr = new OutputStreamWriter(new FileOutputStream("out.txt"));
OutputStreamWriter isr2 = new OutputStreamWriter(new FileOutputStream("out.txt") , "GBK");

指定编码写出:

public class OutputDemo {
	public static void main(String[] args) throws IOException {
		// 定义文件路径
		String FileName = "E:\\out.txt";
		// 创建流对象,默认UTF8编码
		OutputStreamWriter osw = new OutputStreamWriter(new FileOutputStream(FileName));
		// 写出数据
		osw.write("你好"); // 保存为6个字节
		osw.close();

		// 定义文件路径
		String FileName2 = "E:\\out2.txt";
		// 创建流对象,指定GBK编码
		OutputStreamWriter osw2 = new OutputStreamWriter(new FileOutputStream(FileName2),"GBK");
		// 写出数据
		osw2.write("你好");// 保存为4个字节
		osw2.close();
	}
}

在这里插入图片描述

2.5 练习:转换文件编码

将GBK编码的文本文件,转换为UTF-8编码的文本文件。

  1. 指定GBK编码的转换流,读取文本文件。
  2. 使用UTF-8编码的转换流,写出文本文件。
public class TransDemo {
	public static void main(String[] args) {
		// 1.定义文件路径
		String srcFile = "file_gbk.txt";
		String destFile = "file_utf8.txt";
		// 2.创建流对象
		// 2.1 转换输入流,指定GBK编码
		InputStreamReader isr = new InputStreamReader(new FileInputStream(srcFile) , "GBK");
		// 2.2 转换输出流,默认utf8编码
		OutputStreamWriter osw = new OutputStreamWriter(new FileOutputStream(destFile));
		// 3.读写数据
		// 3.1 定义数组
		char[] cbuf = new char[1024];
		// 3.2 定义长度
		int len;
		// 3.3 循环读取
		while ((len = isr.read(cbuf))!=1) {
		// 循环写出
			osw.write(cbuf,0,len);
		}
		// 4.释放资源
		osw.close();
		isr.close();
	}
}
发布了37 篇原创文章 · 获赞 30 · 访问量 1143

猜你喜欢

转载自blog.csdn.net/myjess/article/details/104292639