练习 上机练习 0需求说明 口C盘根目录下的文件中保存了学员的姓名信息,请编 程实现将此文件复制到D盘根目录下 口分析 口定义方法, 源文件和目标文件作为参数 。使用File InputStream 读文本文件 使用File0utputStream写文本文件
时间: 2024-04-07 14:33:52 浏览: 15
在Java中,你可以使用 `FileInputStream` 和 `FileOutputStream` 类来实现文件的复制操作。以下是一个示例代码:
```java
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
public class FileCopyExample {
public static void main(String[] args) {
String sourceFile = "C:\\source.txt"; // 源文件路径
String targetFile = "D:\\target.txt"; // 目标文件路径
try {
FileInputStream fis = new FileInputStream(sourceFile);
FileOutputStream fos = new FileOutputStream(targetFile);
byte[] buffer = new byte[1024];
int bytesRead;
while ((bytesRead = fis.read(buffer)) != -1) {
fos.write(buffer, 0, bytesRead);
}
System.out.println("文件复制成功!");
fis.close();
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
```
在上面的代码中,我们首先定义了源文件路径和目标文件路径。然后,使用 `FileInputStream` 和 `FileOutputStream` 分别创建输入流和输出流。接下来,我们使用一个缓冲区(`buffer`)来读取源文件的内容,并将其写入目标文件。最后,关闭输入流和输出流。
你可以将源文件路径和目标文件路径修改为你实际的文件路径,然后运行代码,即可将源文件复制到目标文件中。记得要处理可能抛出的异常,以确保程序的健壮性。
相关推荐
![](https://img-home.csdnimg.cn/images/20210720083646.png)
![doc](https://img-home.csdnimg.cn/images/20210720083327.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)