把d:\\bbb.mp4复制到当前项目目录下的copy.mp4中 分别用FileInputStream和BufferedInputStream类中的两种read()方法,共四种方式复制并比较效率。 写出Java程序代码并给出注释 2023/5/29 12:37:45
时间: 2024-02-17 21:00:57 浏览: 19
好的,这是您的问题,下面是回答:
首先,需要导入相关的IO库,包括FileInputStream、BufferedInputStream、FileOutputStream和BufferedOutputStream。
接下来,可以按照以下步骤实现复制文件的操作:
1. 创建FileInputStream对象,读取源文件中的数据。
2. 创建BufferedInputStream对象,提高读取效率。
3. 创建FileOutputStream对象,写入目标文件中的数据。
4. 创建BufferedOutputStream对象,提高写入效率。
5. 使用read()方法或read(byte[] b)方法读取源文件中的数据。
6. 使用write()方法或write(byte[] b)方法将数据写入目标文件中。
7. 关闭相关的流对象。
下面是Java程序代码和注释:
```java
import java.io.*;
public class FileCopyDemo {
public static void main(String[] args) {
// 源文件路径
String sourceFile = "d:\\bbb.mp4";
// 目标文件路径
String targetFile = "copy.mp4";
try {
// 1. 创建FileInputStream对象,读取源文件中的数据
FileInputStream fis = new FileInputStream(sourceFile);
// 2. 创建BufferedInputStream对象,提高读取效率
BufferedInputStream bis = new BufferedInputStream(fis);
// 3. 创建FileOutputStream对象,写入目标文件中的数据
FileOutputStream fos = new FileOutputStream(targetFile);
// 4. 创建BufferedOutputStream对象,提高写入效率
BufferedOutputStream bos = new BufferedOutputStream(fos);
// 读取源文件数据的方式1:使用read()方法读取
long startTime1 = System.currentTimeMillis(); // 记录开始时间
int len1;
while ((len1 = bis.read()) != -1) {
bos.write(len1); // 将读取的数据写入目标文件
}
long endTime1 = System.currentTimeMillis(); // 记录结束时间
System.out.println("方式1总共耗时:" + (endTime1 - startTime1) + "毫秒");
// 读取源文件数据的方式2:使用read(byte[] b)方法读取
long startTime2 = System.currentTimeMillis(); // 记录开始时间
int len2;
byte[] buffer = new byte[1024]; // 缓冲区大小为1KB
while ((len2 = bis.read(buffer)) != -1) {
bos.write(buffer, 0, len2); // 将读取的数据写入目标文件
}
long endTime2 = System.currentTimeMillis(); // 记录结束时间
System.out.println("方式2总共耗时:" + (endTime2 - startTime2) + "毫秒");
// 关闭流对象
bis.close();
bos.close();
fis.close();
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
```
通过比较方式1和方式2的耗时,可以得出不同读取方式的效率差异。在实际操作中,可以根据实际需求选择最合适的读取方式。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://img-home.csdnimg.cn/images/20210720083646.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://img-home.csdnimg.cn/images/20210720083646.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![docx](https://img-home.csdnimg.cn/images/20210720083331.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)