编写一个Java应用程序,将图片pic.jpg从C盘复制到D盘,并命名为des.jpg。
时间: 2024-02-18 19:00:23 浏览: 35
以下是一个实现将图片pic.jpg从C盘复制到D盘,并命名为des.jpg的 Java 应用程序的示例代码:
```java
import java.io.*;
public class FileCopy {
public static void main(String[] args) {
String sourceFile = "C:/pic.jpg";
String destinationFile = "D:/des.jpg";
try (InputStream inputStream = new FileInputStream(sourceFile);
OutputStream outputStream = new FileOutputStream(destinationFile)) {
byte[] buffer = new byte[1024];
int length;
while ((length = inputStream.read(buffer)) > 0) {
outputStream.write(buffer, 0, length);
}
System.out.println("File copied successfully!");
} catch (IOException e) {
e.printStackTrace();
}
}
}
```
在这个程序中,我们首先指定源文件和目标文件的路径,然后使用 FileInputStream 和 FileOutputStream 创建输入输出流。接着,我们使用一个缓冲区来读取源文件中的数据,并将其写入目标文件中。最后,我们关闭输入输出流,并在控制台输出一条消息来表示文件已经成功复制。
需要注意的是,在使用输入输出流的时候,需要使用 try-with-resources 语句来确保流会被及时关闭。同时,在处理 IOException 异常的时候,也需要进行适当的处理。