编写一个java程序,将图片pic.jpg从c盘复制到D盘,并命名为des.jpg
时间: 2024-02-09 12:10:52 浏览: 61
好的,您可以参考以下的Java代码实现:
```java
import java.io.*;
public class CopyImage {
public static void main(String[] args) {
String sourcePath = "C:\\pic.jpg"; // 源文件路径
String destPath = "D:\\des.jpg"; // 目标文件路径
File sourceFile = new File(sourcePath);
File destFile = new File(destPath);
try {
InputStream in = new FileInputStream(sourceFile);
OutputStream out = new FileOutputStream(destFile);
byte[] buffer = new byte[1024];
int length;
while ((length = in.read(buffer)) > 0) {
out.write(buffer, 0, length);
}
in.close();
out.close();
System.out.println("文件复制成功!");
} catch (IOException e) {
e.printStackTrace();
}
}
}
```
在上面的代码中,我们首先定义了源文件和目标文件的路径,然后通过File类创建相应的文件对象。接着,我们使用FileInputStream和FileOutputStream类分别创建输入流和输出流,用于读取源文件和写入目标文件。在while循环中,我们不断读取源文件中的数据,并将其写入目标文件中。最后,我们关闭输入流和输出流,并输出复制成功的提示信息。
注意:在运行程序时,需要保证C盘存在名为pic.jpg的图片文件,否则会出现FileNotFoundException异常。