java实现对图片的复制
时间: 2023-10-09 17:15:24 浏览: 52
Java实现对图片的复制可以使用以下代码:
```
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
public class ImageCopy {
public static void main(String[] args) {
String sourcePath = "path/to/source/image.jpg";
String destPath = "path/to/destination/image.jpg";
copyImage(sourcePath, destPath);
}
public static void copyImage(String sourcePath, String destPath) {
try {
File sourceFile = new File(sourcePath);
File destFile = new File(destPath);
FileInputStream fis = new FileInputStream(sourceFile);
FileOutputStream fos = new FileOutputStream(destFile);
byte[] buffer = new byte[1024];
int length;
while ((length = fis.read(buffer)) > 0) {
fos.write(buffer, 0, length);
}
fis.close();
fos.close();
System.out.println("Image copied successfully!");
} catch (IOException e) {
e.printStackTrace();
}
}
}
```
在上面的代码中,我们使用`FileInputStream`和`FileOutputStream`类来读取和写入文件内容。我们创建了两个`File`对象来表示源文件和目标文件,并在`FileInputStream`和`FileOutputStream`的构造函数中传递这些对象。然后,我们使用一个`byte`数组作为缓冲区来读取和写入文件内容。最后,我们在完成读取和写入操作后关闭文件输入和输出流。