Merge Two text files line by line using java

merge multiple text files into one java
how to merge two csv files in java
java program to read a text file and write to another file
merge two xml files using java
merging two csv files with a common column java
how to use two files in java
read two files in java
how to merge two word documents in java

First text file A.txt;

asdfghjklqw12345 qwe3456789 asdfghjklqw12345 qwe3456789

Second text file B.txt;

|Record 1: Rejected - Error on table AUTHORIZATION_TBL, column AUTH_DATE.ORA-01843: not a valid month| |Record 2: Rejected - Error on table AUTHORIZATION_TBL, column AUTH_DATE.ORA-01843: not a valid month|

Third text file C.txt;

asdfghjklqw12345 qwe3456789 |Record 1: Rejected - Error on table AUTHORIZATION_TBL, column AUTH_DATE.ORA-01843: not a valid month|

asdfghjklqw12345 qwe3456789 |Record 2: Rejected - Error on table AUTHORIZATION_TBL, column AUTH_DATE.ORA-01843: not a valid month|

for the above situation where I want to merge two lines from two different text files into one line.My code is below

    List<FileInputStream> inputs = new ArrayList<FileInputStream>();
    File file1 = new File("C:/Users/dell/Desktop/Test/input1.txt");
    File file2 = new File("C:/Users/dell/Desktop/Test/Test.txt");

    FileInputStream fis1;
    FileInputStream fis2;

    try {
        fis1 = new FileInputStream(file1);
        fis2= new FileInputStream(file2);

        inputs.add(fis1);
        inputs.add(fis2);

    } catch (FileNotFoundException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    int total = (int) (file1.length() + file2.length());
    System.out.println("total length is " + total);

    SequenceInputStream sis = new                                                            SequenceInputStream(Collections.enumeration(inputs));
    try {
        System.out.println("SequenceInputStream.available() = "+ sis.available());

        byte[] merge = new byte[total];

        int soFar = 0;
        do {
            soFar += sis.read(merge,total - soFar, soFar);
        } while (soFar != total);
        DataOutputStream dos = new DataOutputStream(new        FileOutputStream("C:/Users/dell/Desktop/Test/C.txt"));
        soFar = 0;
        dos.write(merge, 0, merge.length);
        dos.close();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

Here is code:

public class MergeText {
    public static void main(String[] args) throws IOException{
        String output="";
        try(Scanner sc1=new Scanner((new File("A.txt")));
        Scanner sc2=new Scanner((new File("B.txt")))){

        while(sc1.hasNext() || sc2.hasNext()){
            output+=sc1.next() +" "+ sc2.next();
            output+="\n";
        }

        }

        try(PrintWriter pw=new PrintWriter(new File("C.txt"))){
        pw.write(output);
        }        
    }
}

Merge Two text files line by line using java, Java program to store a Student Information in a File using AWT · Java program to delete duplicate lines in text file · Java program to read all mobile numbers  Java program to merge two files alternatively into third file. Create PrintWriter object for file3.txt. Open BufferedReader for file1.txt. Open BufferedReader for file2.txt. Run a loop to copy each line of file1.txt and then file2.txt to file3.txt. Flush PrintWriter stream and close resources.

You might want to have a look at BufferedReader and BufferedWriter. Show us what you tried and where you are stuck and we are happy to provide more help.

Java program to merge two files alternatively into , I often need to merge multiple files into one in Java. String mergedFilePath = "/​home/programcreek/Desktop/m"; File[] files = new File[2]; files[0] = new  Merge Files in Java. I often need to merge multiple files into one in Java. So I write a reusable method to do this job. It works very well for me to merge a set of txt files. The method accepts an array of File and the merged file path. After running the method, the set of files to be merged will be merged into the specified file.

Merging all txt file from a folder can be done in the following way:

public static void main(String[] args) throws IOException {
        ArrayList<String> list = new ArrayList<String>();

        //Reading data files
        try {

            File folder = new File("path/inputFolder");
            File[] listOfFiles = folder.listFiles();

            for (int i = 0; i < listOfFiles.length; i++) {
                File file = listOfFiles[i];
                if (file.isFile() && file.getName().endsWith(".txt")) {
                    BufferedReader t = new BufferedReader (new FileReader (file));
                    String s = null;
                    while ((s = t.readLine()) != null) {                         
                        list.add(s);        
                    }
                    t.close();
                } 
            }
        }
        catch (IOException e) {
            e.printStackTrace();
        }

        //Writing merged data file
        BufferedWriter writer=null;
        writer = new BufferedWriter(new FileWriter("data.output/merged-output.txt"));
        String listWord;              
        for (int i = 0; i< list.size(); i++)
        {
            listWord = list.get(i);
            writer.write(listWord);
            writer.write("\n");
        }
        System.out.println("complited");
        writer.flush();
        writer.close();    
    }

Merge Files in Java, Java program to compare two text files line by line in java, Compare two text files line by line, Java I/O How to append text to a file in java? Java program to merge two files into a third file. Create PrintWriter object for file3.txt. Open BufferedReader for file1.txt. Run a loop to copy each line of file1.txt to file3.txt. Open BufferedReader for file2.txt. Run a loop to copy each line of file2.txt to file3.txt. Flush PrintWriter stream

Improved on Masudul's answer to avoid compilation errors:

import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Scanner;

public class MergeText {
    public static void main(String[] args) throws IOException {
        StringBuilder output = new StringBuilder();
        try (Scanner sc1 = new Scanner((new File("C:\\Users\\YourName\\Desktop\\A.txt")));
             Scanner sc2 = new Scanner((new File("C:\\Users\\YourName\\Desktop\\B.txt")))) {

            while (sc1.hasNext() || sc2.hasNext()) {
                String s1 = (sc1.hasNext() ? sc1.next() : "");
                String s2 = (sc2.hasNext() ? sc2.next() : "");
                output.append(s1).append(" ").append(s2);
                output.append("\n");
            }
        }
        try (PrintWriter pw = new PrintWriter(new File("C:\\Users\\mathe\\Desktop\\Fielddata\\RESULT.txt"))) {
            pw.write(output.toString());
        }
    }
}

How To Compare Two Text Files Line By Line In Java?, Java program to merge two or more files alternatively into third file writer = new FileWriter("D://result.txt"); String str[] = new String[3]; while (sc1. If the above three files are in the same directly you can rewrite the sample  Java read file line by line using Files.readAllLines() Files.readAllLines() is a utility method of the Java NIO’s Files class that reads all the lines of a file and returns a List<String> containing each line. It internally uses BufferedReader to read the file.

Java program to merge two or more files alternatively into third file, Prerequisite : PrintWriter , BufferedReader Let the given two files be file1.txt and third file say file3.txt but merging should be done by line by line alternatively. To successfully run the below program file1.txt and file2.txt must exits in same  Insert a multi-selection by pressing Shift + Alt + Arrow Down 4 times, till the bottom line of the text block. Press Arrow Down one more time (without Shift or Alt) in order to move the multi-selection one line down. Press Enter to add five lines to the text block. Paste (Ctrl + V) to combine both text blocks.

Java program to merge two files alternatively , If your files are known to be text files, and the default encoding for the system is OK, mergeFiles(final File output, final File inputfile1, final File inputfile2) throws It also preserves the end-of-line system used in the source files, rather However, you can use try-with-resources(if you have Java 7 or later) to  Java Programming Code to Merge Two Files. Following Java Program ask to the user to enter the first and second file name with extension to merge its content and then ask to the user to enter the third file name with extension to store the merged content inside it: /* Java Program Example - Merge Two Files */ import java.io.*; import java.util.Scanner; public class JavaProgram { public static void main (String args []) { String srcy, srcz, merge; Scanner scan = new Scanner (System.in);

Copying contents of two files into one file/ bufferedReader close calls, The other options are for stripping lines from the top of text files or adding line spacing to the bottom. Each merged text file will be saved in the same folder with​  In BufferedReader use readLine () method to read file line by line to String. readLine () method returns null at the end of the file. See the below simple example how to read file line by line with BufferedReader.

Comments
  • What you are trying to do?
  • have you tried anything so far? if yes, please show us!
  • And what have you tried to achieve it?
  • 1 2 3 4 5 are separate lines? Your specification doesn't correspond with the examples. Also share your code, please.
  • Hi Thomas Please help me to find out a solution to my above question...Its urgent
  • I'm not the downvoter, but your while should have && instead of ||. Not to mention StringBuilder/StringBuffer instead of += on strings. So yeah, he had reasons. Enough reasons!
  • I am getting this exception --->java.util.NoSuchElementException,at line java.util.NoSuchElementException
  • @AvisekPanda Provide some code and stack trace. You should update your question.