Computer >> 컴퓨터 >  >> 프로그램 작성 >> Java

두 개 이상의 파일을 번갈아 세 번째 파일로 병합하는 Java 프로그램

<시간/>

다음과 같은 세 개의 파일이 있다고 가정합니다. -

출력1.txt

Hello how are you

출력2.txt

Welcome to Tutorialspoint

출력3.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