用java编写程序实现将一个文件内容追加到另一个文件内容后,如将D盘file文件夹下的f1.txt追加到E盘根目录下的f2.txt中。(必须异常处理)
时间: 2024-03-03 22:52:07 浏览: 58
好的,以下是Java代码实现:
```java
import java.io.*;
public class FileAppend {
public static void main(String[] args) {
String filePath1 = "D:/file/f1.txt";
String filePath2 = "E:/f2.txt";
File file1 = new File(filePath1);
File file2 = new File(filePath2);
FileReader fileReader = null;
FileWriter fileWriter = null;
try {
fileReader = new FileReader(file1);
fileWriter = new FileWriter(file2, true);
char[] buffer = new char[1024];
int len = 0;
while ((len = fileReader.read(buffer)) != -1) {
fileWriter.write(buffer, 0, len);
}
System.out.println("文件追加成功!");
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (fileReader != null) {
fileReader.close();
}
if (fileWriter != null) {
fileWriter.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
```
该代码通过FileReader和FileWriter类,实现了将D盘file文件夹下的f1.txt文件内容追加到E盘根目录下的f2.txt文件中。其中,FileWriter构造方法的第二个参数设置为true,表示在打开文件时将其附加到文件末尾。同时,代码还对文件读写过程中可能抛出的IOException异常进行了处理。
阅读全文
相关推荐
![java](https://img-home.csdnimg.cn/images/20250102104920.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)
![pptx](https://img-home.csdnimg.cn/images/20241231044947.png)
![docx](https://img-home.csdnimg.cn/images/20241231044901.png)
![ppt](https://img-home.csdnimg.cn/images/20241231044937.png)
![text/rtf](https://img-home.csdnimg.cn/images/20250102104920.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)