📅  最后修改于: 2023-12-03 15:32:05.203000             🧑  作者: Mango
在Java开发中,有时需要将两个文件交替合并到第三个文件中。本文将为您介绍一个Java程序,可以帮助您实现这个需求。
File file1 = new File("file1.txt");
File file2 = new File("file2.txt");
File outputFile = new File("output.txt");
try {
FileInputStream fis1 = new FileInputStream(file1);
FileInputStream fis2 = new FileInputStream(file2);
FileOutputStream fos = new FileOutputStream(outputFile);
int i = 0;
while ((i = fis1.read()) != -1) {
fos.write(i);
}
fis1.close();
while ((i = fis2.read()) != -1) {
fos.write(i);
}
fis2.close();
fos.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
if(outputFile.exists()) {
System.out.println("文件合并成功!");
} else {
System.out.println("文件合并失败!");
}
下面是完整的Java代码:
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
public class Main {
public static void main(String[] args) {
File file1 = new File("file1.txt");
File file2 = new File("file2.txt");
File outputFile = new File("output.txt");
try {
FileInputStream fis1 = new FileInputStream(file1);
FileInputStream fis2 = new FileInputStream(file2);
FileOutputStream fos = new FileOutputStream(outputFile);
int i = 0;
while ((i = fis1.read()) != -1) {
fos.write(i);
}
fis1.close();
while ((i = fis2.read()) != -1) {
fos.write(i);
}
fis2.close();
fos.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
if(outputFile.exists()) {
System.out.println("文件合并成功!");
} else {
System.out.println("文件合并失败!");
}
}
}
本文为您介绍了一个Java程序,可以将两个文件交替合并到第三个文件中。不过,在实际开发中,为了保证程序的健壮性,我们还需要加入一些异常处理、输入参数判断等代码。