Java学习回忆录-基础理论-拷贝文件的四种方式
以拷贝一首歌曲来测试。
方案一: 使用普通流,没缓冲(淘汰)
4分钟.
// 2. 创建字节输入流. ->读取源文件.
FileInputStream fis = new FileInputStream(srcFile);
// 创建字节输出流 ->写出数据. 数据来源不再是程序中写死的,而是依赖于输入流读取的.
FileOutputStream fos = new FileOutputStream(destFile);
int data;
// 3. 循环读取源文件的数据.
while ((data = fis.read()) != -1) {
// 将输出写出,写出到目的地.
fos.write(data);
}
// 4. 关闭流.
fis.close();
fos.close();
方案二: 使用普通流,自建缓冲. (可以)
294毫秒. 0.3 秒
// 1. 创建字节输入流. ->读取源文件.
FileInputStream fis = new FileInputStream(srcFile);
// 2.创建字节输出流 ->写出数据. 数据来源不再是程序中写死的,而是依赖于输入流读取的.
FileOutputStream fos = new FileOutputStream(destFile);
// 3. 定义字节数组,作为缓冲.
byte[] buff = new byte[1024]; // 1024byte ->1k
// 4. 定义变量,记录字节输入流读取到有效字节数.
int len;
// 5. 循环读取.
while ((len = fis.read(buff)) != -1) {
// 6. 将存储到数组中的有效数据,使用字节输出流写出.
fos.write(buff, 0, len);
}
// 7. 关闭流.
fis.close();
fos.close();
方案三: 使用了java 提供的字节缓冲流.(淘汰)
注意: 只是基本的read 和write . 一个字节读,一个字节写...
1950毫秒
怎么自带缓冲比普通流,自建数组作为缓冲的还要慢? 对比是不公平的.
// 1. 字节输入流
FileInputStream fis = new FileInputStream(srcFile);
// 2. 创建字节输出流
FileOutputStream fos = new FileOutputStream(destFile);
// 3. 创建字节缓冲输入流 ->是缓冲流,可以针对不带缓冲的普通字节输入流,加入缓冲功能,构造方法需要一个字节输出流
BufferedInputStream buffis = new BufferedInputStream(fis);
// 4. 创建字节缓冲输出流. ->该流需要通过构造,关联字节输出流.
BufferedOutputStream buffos = new BufferedOutputStream(fos);
// 5. 测试java 自带的字节缓冲流性能如何.
// 6读取和写出数据.拷贝文件.
int data;
// 使用缓冲流,一次读取一个字节.
while ((data = buffis.read()) != -1) {
buffos.write(data);
}
// 7. 关闭流.
buffis.close();
buffos.close();
方案四: 使用了java 提供的字节缓冲流. (建议) ->最快
注意: 升级了读取和写出的方式. 批量读取和写出.
定义字节输出. 批量读取和写出.
read(byte[] b);
write(byte[] b,int start ,int len);
82毫秒
private static void copyFileByBuffer2(File srcFile, File destFile) throws IOException {
// 1. 字节输入流
FileInputStream fis = new FileInputStream(srcFile);
// 2. 创建字节输出流
FileOutputStream fos = new FileOutputStream(destFile);
// 3. 创建字节缓冲输入流 ->是缓冲流,可以针对不带缓冲的普通字节输入流,加入缓冲功能,构造方法需要一个字节输出流
BufferedInputStream buffis = new BufferedInputStream(fis);
// 4. 创建字节缓冲输出流. ->该流需要通过构造,关联字节输出流.
BufferedOutputStream buffos = new BufferedOutputStream(fos);
// 5. 不是使用缓冲流一个读取一个字节.
byte[] buff = new byte[1024];
int len;
while ((len = buffis.read(buff)) != -1) {
buffos.write(buff, 0, len);
}
// 7. 关闭流.
buffis.close();
buffos.close();
















