温馨提示×

java怎么合并两个文件

小亿
302
2023-09-14 16:58:40
栏目: 编程语言

在Java中,可以使用以下方法合并两个文件:

  1. 使用BufferedReader和BufferedWriter
import java.io.*;
public class FileMerge {
public static void main(String[] args) {
String file1Path = "file1.txt";
String file2Path = "file2.txt";
String mergedFilePath = "mergedFile.txt";
try {
BufferedReader reader1 = new BufferedReader(new FileReader(file1Path));
BufferedReader reader2 = new BufferedReader(new FileReader(file2Path));
BufferedWriter writer = new BufferedWriter(new FileWriter(mergedFilePath));
String line;
// 读取并写入file1的内容
while ((line = reader1.readLine()) != null) {
writer.write(line);
writer.newLine();
}
// 读取并写入file2的内容
while ((line = reader2.readLine()) != null) {
writer.write(line);
writer.newLine();
}
reader1.close();
reader2.close();
writer.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
  1. 使用FileInputStream和FileOutputStream
import java.io.*;
public class FileMerge {
public static void main(String[] args) {
String file1Path = "file1.txt";
String file2Path = "file2.txt";
String mergedFilePath = "mergedFile.txt";
try {
FileInputStream file1InputStream = new FileInputStream(file1Path);
FileInputStream file2InputStream = new FileInputStream(file2Path);
FileOutputStream mergedFileOutputStream = new FileOutputStream(mergedFilePath);
byte[] buffer = new byte[1024];
int bytesRead;
// 读取并写入file1的内容
while ((bytesRead = file1InputStream.read(buffer)) != -1) {
mergedFileOutputStream.write(buffer, 0, bytesRead);
}
// 读取并写入file2的内容
while ((bytesRead = file2InputStream.read(buffer)) != -1) {
mergedFileOutputStream.write(buffer, 0, bytesRead);
}
file1InputStream.close();
file2InputStream.close();
mergedFileOutputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}

这些代码示例将两个文件的内容逐行或逐字节读取并写入到第三个文件中,从而实现了文件的合并。在实际使用时,可以根据实际需求进行适当的修改。

0