s-day10-缓冲流的概述&使用缓冲流复制文件(一次读写一个字节)
This commit is contained in:
@@ -0,0 +1,79 @@
|
||||
package com.inmind.buffered01;
|
||||
|
||||
import java.io.BufferedInputStream;
|
||||
import java.io.BufferedOutputStream;
|
||||
import java.io.FileInputStream;
|
||||
import java.io.FileOutputStream;
|
||||
|
||||
/*
|
||||
1.缓冲流的介绍
|
||||
缓冲流:基于字节字符流,本身本身没有读写功能,底层封装了一8192长度的缓冲区(数组),提高读写效率,也叫高效流
|
||||
|
||||
字节缓冲流: BufferedInputStream BufferedOutputStream
|
||||
字符缓冲流: BufferedReader BufferedWriter
|
||||
------------------------------------------------------------------------------------
|
||||
字节缓冲流的基本使用以及使用缓冲流复制文件(一次读写一个字节)
|
||||
字节缓冲输入流:BufferedInputStream
|
||||
构造方法:
|
||||
BufferedInputStream(InputStream in) 创建一个 BufferedInputStream并保存其参数,输入流 in供以后使用。
|
||||
常用方法:
|
||||
int read() :读取一个字节数据
|
||||
int read(byte[] bytes) : 读取一个字节数组
|
||||
|
||||
字节缓冲输出流:BufferedOutputStream
|
||||
构造方法:
|
||||
BufferedOutputStream(OutputStream out) 创建一个新的缓冲输出流,以将数据写入指定的底层输出流。
|
||||
常用方法:
|
||||
void write(int b) 将指定的字节写入缓冲的输出流。
|
||||
public void write(byte[] b)
|
||||
void write(byte[] b, int off, int len) 从偏移量 off开始的指定字节数组写入 len字节到缓冲输出流。
|
||||
|
||||
*/
|
||||
public class Demo01 {
|
||||
public static void main(String[] args) throws Exception {
|
||||
//使用缓冲流复制文件
|
||||
//创建字节缓冲输入流
|
||||
FileInputStream fis = new FileInputStream("1.jpg");
|
||||
BufferedInputStream bis = new BufferedInputStream(fis);
|
||||
//创建字节缓冲输出流
|
||||
BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream("2.jpg"));
|
||||
long start = System.currentTimeMillis();
|
||||
//缓冲流一次读写一个字节,使用43ms
|
||||
int c ;//保存读取的一个字节数据
|
||||
//缓冲流不停读写
|
||||
while ((c = bis.read()) != -1) {
|
||||
bos.write(c);
|
||||
}
|
||||
long end = System.currentTimeMillis();
|
||||
System.out.println("复制所需的毫秒值:"+(end-start));
|
||||
|
||||
bis.close();
|
||||
bos.close();
|
||||
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
//使用字节输入输出流进行一次读写一个字节,复制文件 6477ms
|
||||
public static void method(String[] args)throws Exception {
|
||||
//1.创建字节输入流
|
||||
FileInputStream fis = new FileInputStream("D:\\io_test\\upload\\1.jpg");
|
||||
//2.创建字节输出流
|
||||
FileOutputStream fos = new FileOutputStream("1.jpg");
|
||||
//3.不停地读写到另一个文件中(边读边写)
|
||||
long start = System.currentTimeMillis();
|
||||
//方式一:一次读写一个字节
|
||||
int c;//用来记录读取的字节数据
|
||||
while ((c = fis.read()) != -1) {
|
||||
fos.write(c);
|
||||
}
|
||||
long end = System.currentTimeMillis();
|
||||
System.out.println("复制所需的毫秒值:"+(end-start));
|
||||
//4.资源释放
|
||||
fis.close();
|
||||
fos.close();
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user