2016-08-29 2 views
4

무작위 화 된 두 개의 텍스트 파일을 비교하고 두 파일 모두에서 일치하는 행을 인쇄하려고합니다. 파일 1 :Java와 무작위 순서로 두 텍스트 파일 비교

Student1 
Student2 
Student3 
Student4 

파일 2 :

Student1 
Student2 

내 코드는 다음과 같이

Student6 
Student1 
Student2 

나는 출력을 할 수 있습니다.

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

    String first = "file1.txt"; 
    String second = "file2.txt"; 
    BufferedReader fBr = new BufferedReader(new FileReader(first)); 
    BufferedReader sBr = new BufferedReader(new FileReader(second)); 




    PrintWriter writer = new PrintWriter("test.txt", "UTF-8"); 
    while ((first = fBr.readLine()) != null) { 
     String partOne1 = fBr.readLine(); 
     String partTwo1 = sBr.readLine(); 
     while ((second = sBr.readLine()) != null) { 
       System.out.println(first); 
       writer.println(first); 
       break;     

     } 
    } 


    writer.close(); 
    fBr.close(); 
    sBr.close(); 
+0

첫 번째 파일의 모든 행을'ArrayList '로 읽을 수 있으며 두 번째 파일의 각 문자열이 ArrayList에있는 경우 두 번째로 읽는 동안 http://www.tutorialspot.com/java/util/arraylist_indexof.htm – Slavik

+3

정렬 및 병합 ... google it up –

답변

5

매우 간단합니다 =) 첫 번째 파일의 모든 결과를 저장하고 두 번째 줄의 모든 파일과 비교하십시오. 그것은 다음과 같이 될 것입니다 :

package com.company; 

import java.io.BufferedReader; 
import java.io.FileReader; 
import java.io.IOException; 
import java.util.ArrayList; 

public class Main { 

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

     String first = "file1.txt"; 
     String second = "file2.txt"; 
     BufferedReader fBr = new BufferedReader(new FileReader(first)); 
     BufferedReader sBr = new BufferedReader(new FileReader(second)); 

     ArrayList<String> strings = new ArrayList<String>(); 

     while ((first = fBr.readLine()) != null) { 
      strings.add(first); 
     } 
     fBr.close(); 

     while ((second = sBr.readLine()) != null) { 
      if (strings.contains(second)) { 
       System.out.println(second); 
      } 
     } 
     sBr.close(); 
    } 
} 

그것은 가능하면 메모리를 사용하는 것이 좋습니다, 당신의 '동안'다른 동안 내부에 너무 오래 시간과 obfuskate 논리를 작업 할 수 있습니다.

1

Java8을 사용하는 경우 다음은이 논리를 구현하는 간결한 방법입니다. 이 옵션은 Java8에만 적용됩니다. 그것은 상용구 코드를 많이 사용하지 않고 사용할 수있는 람다 표현식과 기능을 사용합니다. 당신이이어야

List<String> file1Lines = Files.readAllLines(Paths.get("C:\\DevelopmentTools\\student-file1.txt"), Charset.defaultCharset()); 
List<String> file2Lines = Files.readAllLines(Paths.get("C:\\DevelopmentTools\\student-file2.txt"), Charset.defaultCharset()); 

List<String> matchingStrings = file1Lines.stream(). 
filter(studentInfo -> file2Lines.contains(studentInfo)) 
        .collect(Collectors.toList()); 
matchingStrings.forEach(System.out::println); 

인쇄를 즐겁게 찾을 희망 :

Student1 , Student2 
2

또 다른 대안은 두 arraylists 모두 파일을 넣어 일반적인 파일을 얻을 수있는 ArrayList의의 나 retainAll() 메소드를 사용하는 것입니다. 그리고 인쇄 작업이나 다른 작업을 수행하십시오. 당신이 우아한 해결책하려면

public static void main(String[] args) throws IOException { 
    String first = "file1.txt"; 
    String second = "file2.txt"; 
    BufferedReader fBr = new BufferedReader(new FileReader(first)); 
    BufferedReader sBr = new BufferedReader(new FileReader(second)); 

    List<String> firstFile = new ArrayList<>(); 
    List<String> secondFile = new ArrayList<>(); 

    PrintWriter writer = new PrintWriter("test.txt", "UTF-8"); 
    while ((first = fBr.readLine()) != null) { 
     firstFile.add(first); 
    } 
    while ((second = sBr.readLine()) != null) { 
     secondFile.add(second);     
    } 

    List<String> commonFile = new ArrayList<>(firstFile); 
    commonFile.retainAll(secondFile); 
    System.out.println(commonFile); 

    writer.close(); 
    fBr.close(); 
    sBr.close(); 
} 
0

가 :

  1. 정렬을 모두
  2. 가로 정렬 된 목록
  3. 모든

먼저 비교, 이것은 매우 간단합니다. 둘째, 정렬은 매우 최적화되어 있으므로 수동으로 작성된 것보다 빠르며 우아하고 이해하기 쉬운 코드를 생성합니다.

다른 솔루션의 대부분은 O (n * m)입니다. 이 접근법은 작은 상수를 가진 O (n log n + m log m)입니다. 이론적으로 O (n + m)을 산출하지만 너무 큰 상수를 가질 수있는 조회 용 해시 맵을 사용할 수 있습니다.