假设我们有三个文件 -
output1.txt
Hello how are you
output2.txt
Welcome to Tutorialspoint
output3.txt
We provide simply easy learning
以下 Java 示例将上述三个文件的内容交替合并到一个文件中 -
import java.util.Scanner; public class MergingFiles { public static void main(String args[]) throws IOException { Scanner sc1 = new Scanner(new File("D://input1.txt")); Scanner sc2 = new Scanner(new File("D://input2.txt")); Scanner sc3 = new Scanner(new File("D://input3.txt")); FileWriter writer = new FileWriter("D://result.txt"); String str[] = new String[3]; while (sc1.hasNextLine()||sc2.hasNextLine()||sc3.hasNextLine()) { str[0] = sc1.nextLine(); str[1] = sc2.nextLine(); str[2] = sc3.nextLine(); } writer.append(str[0]+"\n"); writer.append(str[1]+"\n"); writer.append(str[2]+"\n"); writer.flush(); System.out.println("Contents added "); } }
Contents added
如果以上三个文件直接在同一个文件中,您可以将示例程序重写为 -
import java.io.File; import java.io.FileWriter; import java.io.IOException; import java.util.Scanner; public class MergingFiles { public static void main(String args[]) throws IOException { //Creating a File object for directory File directoryPath = new File("D:\example"); //List of all files and directories File filesList[] = directoryPath.listFiles(); Scanner sc = null; FileWriter writer = new FileWriter("D://output.txt"); for(File file : filesList) { sc = new Scanner(file); String input; StringBuffer sb = new StringBuffer(); while (sc.hasNextLine()) { input = sc.nextLine(); writer.append(input+"\n"); } writer.flush(); } System.out.println("Contents added "); } }
Contents added
以上是Java程序将两个或多个文件交替合并到第三个文件中的详细内容。更多信息请关注PHP中文网其他相关文章!