在Java中,可以使用以下方法合并兩個文件:
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();
}
}
}
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();
}
}
}
這些代碼示例將兩個文件的內容逐行或逐字節讀取并寫入到第三個文件中,從而實現了文件的合并。在實際使用時,可以根據實際需求進行適當的修改。