Search code examples
javafilewriterseparator

How to write data line by line from the two files into a common file in java


I am facing while merging two files in one (with common content)

public class myFileReader {

    public static void main(String[] args) throws Exception {

        List<String> firstFileList = new ArrayList<String>();
        List<String> secondFileList = new ArrayList<String>();

        List<String> missingRecordsInFile2 = new ArrayList<String>();

        Scanner firstFile = new Scanner(new FileReader(new File("C://write1.txt")));
        Scanner secondFile = new Scanner(new FileReader(new File("C://write2.txt")));

        FileWriter fWriteOne = new FileWriter(new File("C://read1.txt"));


        while (firstFile.hasNext()) {
            firstFileList.add(firstFile.next());
        }

        while (secondFile.hasNext()) {
            secondFileList.add(secondFile.next());
        }

        try {
            for (String fileOne : firstFileList) {
                boolean value = secondFileList.contains(fileOne);
                if (value) {
                    missingRecordsInFile2.add(fileOne);
                    fWriteOne.write(fileOne);
                    fWriteOne.write(System.getProperty("line.separator"));

                }
            }
        } finally {
            fWriteOne.close();
        }
    }
}

For example:

FILE 1:

Yellow wall 
Red Wall 
Green wall
Black wall

FILE 2:

 Red Wall
 Black wall
 Brown wall

RESULTING FILE (My wish):

  Red Wall
  Black wall

But this code write file like:

CURRENT RESULTING FILE:

 Red
 wall
 Black
 wall

Solution

  • You are close to solution but making simple mistake. i.e. you are reading by firstFile.next() which gives you word by word instead of line by line, As you are interested in line by line So use nextLine() Like:

    while (firstFile.hasNext()) {
        firstFileList.add(firstFile.nextLine().trim());
    }
    
    while (secondFile.hasNext()) {
        secondFileList.add(secondFile.nextLine().trim());
    }
    
    try {
        for (String fileOne : firstFileList) {
            boolean value = secondFileList.contains(fileOne);
            if (value) {
                missingRecordsInFile2.add(fileOne);
                fWriteOne.write(fileOne);
                fWriteOne.write(System.getProperty("line.separator"));
            }
        }
    } finally {
        fWriteOne.close();
    }
    

    MORE

    I recommend to use String.Trim() to avoid all extra spaces after your text, As Red Wall_ is not equal to Red Wall because of a single space.