2、有一张图片:1.png,见压缩包:素材.zip,请你解压到某个文件夹下,然后编程完 成以下内容: (1)使用输入输出流将1.png拷贝到同一个文件夹,得到1_out.png (2)要求输入输出使用到缓存流,即要用到BufferedlnputStream和 BufferedOutputStream
时间: 2024-03-11 07:50:01 浏览: 12
以下是Java代码示例:
```java
import java.io.*;
public class CopyImage {
public static void main(String[] args) {
String srcPath = "path/to/1.png"; // 图片源文件路径
String destPath = "path/to/1_out.png"; // 拷贝后的文件路径
try (BufferedInputStream bis = new BufferedInputStream(new FileInputStream(srcPath));
BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(destPath))) {
byte[] buffer = new byte[1024];
int len;
while ((len = bis.read(buffer)) != -1) {
bos.write(buffer, 0, len);
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
```
在上述代码中,首先定义了源文件路径和拷贝后的文件路径,然后使用`BufferedInputStream`和`BufferedOutputStream`对文件进行处理,使用缓存流的目的是增加IO效率。在读写文件时,每次读取1024个字节存入缓冲数组`buffer`,然后使用缓存输出流将缓冲数组中的内容写入到目标文件中。最后需要注意,在使用完输入输出流后,需要使用`try-with-resources`语句来自动关闭流。