Как сравнить 2 файла и удалить несуществующие строки? - PullRequest
1 голос
/ 29 марта 2019

Я пытаюсь удалить несуществующие строки из файла 1 по сравнению с файлом 2

Пример:

Ввод

файл 1

text
example
word

файл 2

example
word

Вывод

файл 1

example
word

Мой код полностью противоположен: он удаляет все повторяющиеся слова в 2 файлах.

Мой фактический вывод:

файл 1

text

код

BufferedReader reader2 = new BufferedReader(new FileReader(file2));
Set<String> lines2 = new HashSet<String>(10000);
String line2;
while ((line2 = reader.readLine()) != null) {
    lines2.add(line);
}
BufferedReader reader = new BufferedReader(new FileReader(file1));
Set<String> lines = new HashSet<String>(10000);
String line;
while ((line = reader.readLine()) != null) {
    lines.add(line);
}
Set set3 = new HashSet(lines);  
set3.removeAll(lines2);

Ответы [ 4 ]

0 голосов
/ 31 марта 2019
public class RemoveLine {

    public static void main(String[] args) throws IOException {
        String file = "../file.txt";
        String file1 = "../file1.txt";
        String file2 = "../file2.txt";

        BufferedReader reader2 = new BufferedReader(new FileReader(file2));
        Set<String> lines2 = new HashSet<String>(10000);
        String line2;
        while ((line2 = reader2.readLine()) != null) {
            lines2.add(line2);
        }

        BufferedReader reader1 = new BufferedReader(new FileReader(file1));
        Set<String> lines1 = new HashSet<String>(10000);
        String line1;
        while ((line1 = reader1.readLine()) != null) {
            lines1.add(line1);
        }

        Set<String> outPut = lines1.stream().filter(l1 -> lines2.stream().anyMatch(l2 -> l2.equals(l1))).collect(Collectors.toSet());


        Charset utf8 = StandardCharsets.UTF_8;

        Files.write(Paths.get(file), outPut, utf8, StandardOpenOption.CREATE);

    }

}
0 голосов
/ 29 марта 2019

Хорошо, вы почти у цели, все, чего вам не хватает, - это еще одна строка кода, по которому вы звоните

lines.removeAll(set3);

, тогда у вас есть набор (строки) с нужным результатом.

0 голосов
/ 29 марта 2019

В исходном коде вы читаете файл 2, затем файл 1 и просто удаляете слова из файла2 из файла1, оставляя одно другое слово.Здесь я выписал код и прокомментировал.Вы должны были иметь набор, который затем удалял это одно слово из полного списка.В своем коде я создал новый набор, на тот случай, если вы захотите перестроить первый набор и оставить его без изменений.

package scrapCompare;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;

public class CompareLines {

public static void main(String[] args) throws IOException {
    // TODO Auto-generated method stub

    //You create a set of words from file 1.
    BufferedReader reader = new BufferedReader(new FileReader("file1"));
    Set<String> lines = new HashSet<String>(10000);
    String line;
    while ((line = reader.readLine()) != null) {
        lines.add(line);
    }
    //You create a set of words from file 2.
    BufferedReader reader2 = new BufferedReader(new FileReader("file2"));
    Set<String> lines2 = new HashSet<String>(10000);
    String line2;
    while ((line2 = reader2.readLine()) != null) {
        lines2.add(line2);
    }

    //In your original code, you create a third set of words equal to file 1, and then delete all the words from file 2.
    //It isolates the one different word, but you stopped there.
    Set set3 = new HashSet(lines);  
    set3.removeAll(lines2);

    lines.removeAll(set3);
    //the answer set is made, in case you want to rebuild the lines set.
    Set <String> answer = lines;
    //iterator for printing to console.
    Iterator<String> itr = answer.iterator();
    //print the answer to console 
    while(itr.hasNext())
    System.out.println(itr.next());

    //close your readers
    reader.close();
    reader2.close();

}

}

0 голосов
/ 29 марта 2019

Вам необходимо пересечение между двумя наборами.Прямо сейчас вы вычисляете симметричную разницу между наборами.

 public static void main(String []args){

    Set<String> file1 = new HashSet<>();
    Set<String> file2 = new HashSet<>();

    file1.add("text");
    file1.add("example");
    file1.add("word");

    file2.add("example");
    file2.add("word");

    Set<String> intersection = new HashSet<>(file1);
    intersection.retainAll(file2);

    System.out.println(intersection);
 }

Выход:

[word, example]
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...