用JAVA复制一个已经存在的文本文件,文件地址为"C:\Users\Lenovo\Desktop\javaexperiment.txt"生成一个新文件
时间: 2023-06-19 13:07:48 浏览: 34
可以使用Java的IO流来实现文本文件的复制。以下是一个示例代码:
```java
import java.io.*;
public class FileCopyExample {
public static void main(String[] args) {
String sourceFile = "C:\\Users\\Lenovo\\Desktop\\javaexperiment.txt";
String destFile = "C:\\Users\\Lenovo\\Desktop\\javaexperiment_copy.txt";
try (InputStream inputStream = new FileInputStream(sourceFile);
OutputStream outputStream = new FileOutputStream(destFile)) {
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` 类来写入目标文件。我们使用一个缓冲区来读取和写入文件数据,每次读取和写入的数据大小为1024字节。最后,我们通过捕获 `IOException` 异常来处理文件操作中可能出现的异常情况。
相关推荐
![](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)