JAVA 中的 IO流、字节流、字符流、缓冲流、转换流、序列流、打印流(五)

144 阅读2分钟

本文已参与「新人创作礼」活动,一起开启掘金创作之路。

  1. 调用BufferedWriter中的write方法,把数据写入到内存缓冲区中
  2. 使用BufferedWriter中的flush方法,把内存缓冲区中的数据,刷新到文件中
  3. 释放资源
练习
BufferedWriter bw = new BufferedWriter(new FileWriter("E:\\test\\b.txt"));
for (int i = 0; i < 10; i++) {
	bw.write("啦啦啦");
	bw.newLine();
}
bw.flush();
bw.close();

1.22 BufferedReader

构造方法:
  • BufferReader(Reader in)
  • BufferReader(Reader in, int sz)
特有的成员方法:

String readline() 读取一行数据 返回值:包含该行内容的字符串,不包含任何行终止符,如果已到达流末尾,则返回null

使用步骤:
  1. 创建缓冲字符输入流对象,构造方法中传入字符输入流
  2. 使用缓冲字符输入流对象中的read/readline读取文本
  3. 释放资源
练习
BufferedReader br = new BufferedReader(new FileReader("E:\\test\\b.txt"));
String line; // 创建读取的文本行,结尾返回null
while ((line = br.readLine()) != null) {
	System.out.println(line);
}
br.close();
字节流 VS 缓冲流
public static void main(String[] args) throws IOException {
	long currentTimeMillis = System.currentTimeMillis();
	// FileOutputStream 
	FileInputStream fis1 = new FileInputStream("E:\\test\\a\\a.jpg");
	FileOutputStream fos1 = new FileOutputStream("E:\\test\\b\\a.jpg");
	byte[] bytes = new byte[1024];
	int len = 0; // 读取到的有效字节个数
	
	while ((len = fis1.read(bytes)) != -1) {
		fos1.write(bytes, 0, len);
	}

	fos1.close();
	fis1.close();

	long doneTimeMillis = System.currentTimeMillis();
	System.out.println("File 复制文件使用了:" + (doneTimeMillis - currentTimeMillis) + "毫秒");

	// BufferedOutputStream
	long currentTimeMillis2 = System.currentTimeMillis();
	BufferedInputStream bis1 = new BufferedInputStream(new FileInputStream("E:\\test\\a\\b.jpg"));
	BufferedOutputStream bos1 = new BufferedOutputStream(new FileOutputStream("E:\\test\\b\\b.jpg"));
	byte[] bytes2 = new byte[1024];
	int len1 = 0;
	while ((len1 = bis1.read(bytes2)) != -1) {
		bos1.write(bytes2, 0, len1);
	}

	bos1.close();
	bis1.close();

	long doneTimeMillis2 = System.currentTimeMillis();
	System.out.println("Buffered 复制文件使用了:" + (doneTimeMillis2 - currentTimeMillis2) + "毫秒");
}
# 输出
File 复制文件使用了:38毫秒
Buffered 复制文件使用了:8毫秒

第四章:转换流

简述:在文件的读取和写入中如果编码不一致有可能导致乱码的问题。转换流中可以指定编码。

1.1 OutputStreamWriter

构造方法:
  • OutputStreamWriter(OutputStream out) 创建使用默认字符编码(UTF-8 )的OutputStreamWriter对象
  • OutputStreamWriter(OutputStream out, String charsetName) 创建使用指定字符集的OutputStreamWriter对象。
使用步骤:
  1. 创建OutputStreamWriter对象,构造方法中传入字节输出流和指定的编码
  2. 使用OutputStreamWriter对象中的write方法,把字符转换成字节存储到缓冲区中
  3. 使用OutputStreamWriter中的flush方法,把缓冲区中的字节刷新到文件中
  4. 释放资源
练习
OutputStreamWriter osw = new OutputStreamWriter(new FileOutputStream("E:\\test\\utf-8.txt"), "UTF-8");
osw.write("你好");
osw.flush();
osw.close();