java把一个txt数据接到另一个txt下面
时间: 2024-02-28 13:56:20 浏览: 22
您可以使用Java中的File类和BufferedReader类以及BufferedWriter类来实现将一个txt文件的内容接到另一个txt文件下面的操作。下面是一个示例代码:
```java
import java.io.*;
public class FileAppend {
public static void main(String[] args) {
try {
File file1 = new File("file1.txt"); // 源文件
File file2 = new File("file2.txt"); // 目标文件
BufferedReader reader = new BufferedReader(new FileReader(file1));
BufferedWriter writer = new BufferedWriter(new FileWriter(file2, true)); // 追加模式
String line = null;
while ((line = reader.readLine()) != null) {
writer.write(line);
writer.newLine(); // 换行
}
reader.close();
writer.close();
System.out.println("文件追加成功!");
} catch (IOException e) {
e.printStackTrace();
}
}
}
```
在这个示例代码中,我们首先定义了源文件和目标文件的File对象,然后使用BufferedReader类读取源文件的内容,并使用BufferedWriter类将读取的内容追加到目标文件的末尾。注意,在写入每一行内容后,我们需要使用writer.newLine()方法换行,这样接到目标文件下面的内容才不会与原有内容挤在一起。在创建BufferedWriter对象时,我们设置第二个参数为true,表示以追加模式打开目标文件。最后,关闭reader和writer对象,并输出追加成功的信息。
相关推荐
![java](https://img-home.csdnimg.cn/images/20210720083646.png)
![text/x-java](https://img-home.csdnimg.cn/images/20210720083646.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.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)