मान लें हमारे पास तीन फाइलें हैं:
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 {
// डायरेक्टरी के लिए File ऑब्जेक्ट बनाना
File directoryPath = new File("D:\\example");
// सभी फाइलों और डायरेक्टरीज़ की लिस्ट
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