在Java中添加两个文本文件的内容可以通过以下步骤实现:
File file1 = new File("path/to/file1.txt");
File file2 = new File("path/to/file2.txt");
try (BufferedReader reader1 = new BufferedReader(new FileReader(file1));
BufferedReader reader2 = new BufferedReader(new FileReader(file2))) {
String line;
while ((line = reader1.readLine()) != null) {
// 逐行处理file1.txt的内容
// ...
}
while ((line = reader2.readLine()) != null) {
// 逐行处理file2.txt的内容
// ...
}
} catch (IOException e) {
e.printStackTrace();
}
List<String> combinedLines = new ArrayList<>();
while ((line = reader1.readLine()) != null) {
combinedLines.add(line);
}
while ((line = reader2.readLine()) != null) {
combinedLines.add(line);
}
File outputFile = new File("path/to/output.txt");
try (BufferedWriter writer = new BufferedWriter(new FileWriter(outputFile))) {
for (String line : combinedLines) {
writer.write(line);
writer.newLine();
}
} catch (IOException e) {
e.printStackTrace();
}
以上就是在Java中添加两个文本文件内容的基本步骤。这种方法适用于处理小型文件,如果文件较大,可能需要采用其他处理方式以避免内存占用过高。
领取专属 10元无门槛券
手把手带您无忧上云