分别以字节流和字节缓冲流完成图片文件的复制(可通过系统自带的图片查看工具打开复制得到的文件,以验证是否复制成功),并打印两种方式分别耗费的时间。
时间: 2024-03-25 14:35:28 浏览: 32
以下是使用字节流和字节缓冲流完成图片文件复制的示例代码:
```java
import java.io.*;
public class ImageCopy {
public static void copyByByteStream(File source, File target) throws IOException {
try (InputStream in = new FileInputStream(source);
OutputStream out = new FileOutputStream(target)) {
int b;
while ((b = in.read()) != -1) {
out.write(b);
}
}
}
public static void copyByBufferedStream(File source, File target) throws IOException {
try (InputStream in = new FileInputStream(source);
OutputStream out = new FileOutputStream(target);
BufferedInputStream bis = new BufferedInputStream(in);
BufferedOutputStream bos = new BufferedOutputStream(out)) {
byte[] buffer = new byte[1024];
int length;
while ((length = bis.read(buffer)) != -1) {
bos.write(buffer, 0, length);
}
}
}
public static void main(String[] args) throws IOException {
File source = new File("source.jpg");
File target1 = new File("target1.jpg");
File target2 = new File("target2.jpg");
long start = System.currentTimeMillis();
copyByByteStream(source, target1);
long end = System.currentTimeMillis();
System.out.println("使用字节流复制图片耗时:" + (end - start) + "ms");
start = System.currentTimeMillis();
copyByBufferedStream(source, target2);
end = System.currentTimeMillis();
System.out.println("使用字节缓冲流复制图片耗时:" + (end - start) + "ms");
}
}
```
代码中,`copyByByteStream` 方法使用字节流复制文件,`copyByBufferedStream` 方法使用字节缓冲流复制文件。程序会输出两种方式分别耗费的时间。
在运行程序时,需要将 `source.jpg` 文件放在程序运行的目录下,程序会将文件复制到同一目录下的 `target1.jpg` 和 `target2.jpg` 文件中。
在复制完成后,可以使用系统自带的图片查看工具打开 `target1.jpg` 和 `target2.jpg` 文件,以验证是否复制成功。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.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://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://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://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)