java使用FilelnputStream和FileOutputStream把图片(D:/src.jpg)复制到目标路径(E:/dest/),使用1024字节的数组作为缓冲。
时间: 2024-05-03 21:17:23 浏览: 7
可以使用以下代码来实现:
```java
import java.io.*;
public class CopyImage {
public static void main(String[] args) {
String srcPath = "D:/src.jpg";
String destPath = "E:/dest/src.jpg";
int bufferSize = 1024;
try (
FileInputStream fis = new FileInputStream(srcPath);
FileOutputStream fos = new FileOutputStream(destPath);
) {
byte[] buffer = new byte[bufferSize];
int len;
while ((len = fis.read(buffer)) != -1) {
fos.write(buffer, 0, len);
}
System.out.println("图片复制完成!");
} catch (IOException e) {
e.printStackTrace();
}
}
}
```
首先定义源文件路径 `srcPath` 和目标文件路径 `destPath`,以及缓冲区大小 `bufferSize`。
接着使用 `FileInputStream` 和 `FileOutputStream` 分别读取源文件和写入目标文件。使用 `try-with-resources` 语句块确保文件流的自动关闭。
在循环中使用字节数组 `buffer` 读取源文件中的内容,并使用 `write` 方法将字节数组写入目标文件中。
最后捕获可能出现的 `IOException` 异常并打印堆栈信息。