📅  最后修改于: 2023-12-03 14:43:03.484000             🧑  作者: Mango
在Java中,将两个文件合并为一个文件有多种实现方式。本文将介绍一种简单的方法,使用Java IO流将两个文件合并为第三个文件。
打开要合并的两个文件和要输出的文件,使用FileInputStream 和 FileOutputStream类打开文件。
File inputFile1 = new File("file1.txt");
File inputFile2 = new File("file2.txt");
File outputFile = new File("output.txt");
InputStream inputStream1 = new FileInputStream(inputFile1);
InputStream inputStream2 = new FileInputStream(inputFile2);
OutputStream outputStream = new FileOutputStream(outputFile);
首先将第一个文件的内容写入输出文件output.txt中 。
int nextByte;
while((nextByte = inputStream1.read()) != -1) {
outputStream.write(nextByte);
}
接下来将第二个文件的内容写入同一文件中。
while((nextByte = inputStream2.read()) != -1) {
outputStream.write(nextByte);
}
关闭流
inputStream1.close();
inputStream2.close();
outputStream.close();
import java.io.*;
public class MergeFiles {
public static void main(String[] args) throws IOException {
// create input and output files
File inputFile1 = new File("file1.txt");
File inputFile2 = new File("file2.txt");
File outputFile = new File("output.txt");
InputStream inputStream1 = new FileInputStream(inputFile1);
InputStream inputStream2 = new FileInputStream(inputFile2);
OutputStream outputStream = new FileOutputStream(outputFile);
// write lines from first file to output file
int nextByte;
while((nextByte = inputStream1.read()) != -1) {
outputStream.write(nextByte);
}
//write lines from second file to output file
while((nextByte = inputStream2.read()) != -1) {
outputStream.write(nextByte);
}
// close input and output stream
inputStream1.close();
inputStream2.close();
outputStream.close();
}
}
这是一个简单的Java程序,以将两个文件合并为第三个文件。实现起来非常容易,只需使用Java IO流打开文件并使用write()方法将内容写入新的文件中。希望本文对你有所帮助,感谢您的阅读!