2014-02-13 2 views
0

두 개의 .txt 파일 (내용물)을 비교하려고하는데,이 코드를 실행하면 응용 프로그램이 무한 루프가됩니다. 왜?자바에서 두 파일 비교하기

public int compareFile(String fILE_ONE2, String fILE_TWO2)throws Exception 
{ 

File f1 = new File(fILE_ONE2); //OUTFILE 
File f2 = new File(fILE_TWO2); //INPUT 

FileReader fR1 = new FileReader(f1); 
FileReader fR2 = new FileReader(f2); 

BufferedReader reader1 = new BufferedReader(fR1); 
BufferedReader reader2 = new BufferedReader(fR2); 

String line1 = null; 
String line2 = null; 
int flag=1; 
while ((flag==1) &&((line1 = reader1.readLine()) != null)&&((line2 = reader2.readLine()) != null)) 
{ 
    if (!line1.equalsIgnoreCase(line2)) 
     flag=0; 
    else 
     flag=1; 
} 
reader1.close(); 
reader2.close(); 
return flag; 


} 
+1

삽입에 println 루프 안쪽 문 그것이 무엇을하고 있는지를 참조하십시오. –

+0

휴식해야합니다. while 루프는 첫 번째 비 - 등가 선에 도달하거나 마지막 선 비교의 결과를 얻습니다. –

+0

코드에 무한 루프가 있다고 생각하지 않습니다. – Kick

답변

0

코드가 무한 루프가 아닌 것처럼 보입니다. 당신은 상관없이 제거 코드에서 확인하고 다음과 같이 코드를 업데이트 할 수 있습니다 동일한 다른 경우와 1 경우가 0를 반환합니다보다 메서드의 반환 형식은 정수

int flag=1; 
while (((line1 = reader1.readLine()) != null)&&((line2 = reader2.readLine()) != null)) 
{ 
    if (!line1.equalsIgnoreCase(line2)) 
    { 
     flag=0; 
     break; 
    } 
} 

으로.

1

코드를 주 프로그램으로 변환했습니다. 이 코드에는 무한 루프가 없습니다.

작은 크기의 텍스트 파일 2 개를 비교한다고 가정합니다.

import java.io.*; 

public class Diff { 
    public static void main(String[] args) throws FileNotFoundException, IOException { 

     File f1 = new File(args[0]);// OUTFILE 
     File f2 = new File(args[1]);// INPUT 

     FileReader fR1 = new FileReader(f1); 
     FileReader fR2 = new FileReader(f2); 

     BufferedReader reader1 = new BufferedReader(fR1); 
     BufferedReader reader2 = new BufferedReader(fR2); 

     String line1 = null; 
     String line2 = null; 
     int flag = 1; 
     while ((flag == 1) && ((line1 = reader1.readLine()) != null) 
       && ((line2 = reader2.readLine()) != null)) { 
      if (!line1.equalsIgnoreCase(line2)) 
       flag = 0; 
     } 
     reader1.close(); 
     reader2.close(); 
     System.out.println("Flag " + flag); 
    } 
} 

2 개의 작은 텍스트 파일로 실행했습니다. 이것이 결과입니다.

javac Diff.java && java Diff a.txt b.txt 
Flag 0 

무한 루프가 있다고 생각되는 경우 문제가 다른 곳에서 발생했을 수 있습니다.

+0

@rick, 왜 무한 루프가 있다고 생각합니까? 아마도 그 문제는 다른 곳에서 있을까요? 자바 메인 라인 애플리케이션에서 약간의 코드를 테스트하기 위해 여기 같은 전략을 사용할 수있다. (JUnit/TestNG가 더 좋지만, 이것도 작동합니다). – Jess

+0

이것은 답변이 아니라 주석이어야합니다. –

+0

안녕하세요 @ 존 Kugelman, 나는 실제로 다른 파일을 테스트하는 시간을 보냈습니다. 또한 OP는 왜 무한 루프가 있었는지 알고 싶었고 나는이 질문에 대답했다고 생각합니다. 나는 OP와 같은 방식으로 코드를 점검하는 전략을 제시했다. – Jess

0

가정 텍스트 파일 입력은 while 루프에 대한 대안의 구현 :

while (true) // Continue while there are equal lines 
{ 
    line1 = reader1.readLine(); 
    line2 = reader2.readLine(); 

    if (line1 == null) // End of file 1 
    { 
     return (line2 == null ? 1 : 0); // Equal only if file 2 also ended 
    } 
    else if (line2 == null) 
    { 
     return 0; // File 2 ended before file 1, so not equal 
    } 
    else if (!line1.equalsIgnoreCase(line2)) // Non-null and different lines 
    { 
     return 0; 
    } 

    // Non-null and equal lines, continue until the input is exhausted 
} 

else if 필요한 것은 아니지만 명료성을 위해 포함된다.

while (true) // Continue while there are equal lines 
{ 
    line1 = reader1.readLine(); 
    line2 = reader2.readLine(); 

    if (line1 == null) // End of file 1 
    { 
     return (line2 == null ? 1 : 0); // Equal only if file 2 also ended 
    } 

    if (!line1.equalsIgnoreCase(line2)) // Different lines, or end of file 2 
    { 
     return 0; 
    } 
} 

루프가 독자가 닫힌 것을 보장하기 위해, try/finally 블록에 배치되어야 님 그렇지 않으면, 위의 코드를 간략화 할 수있다.

0

file2가 file1과 같지만 끝에 여분의 행이 있으면 Jess의 위 메소드가 실패합니다.

이렇게하면됩니다. 당신이 java8를 사용하는 경우

public boolean compareTwoFiles(String file1Path, String file2Path) 
      throws IOException { 

    File file1 = new File(file1Path); 
    File file2 = new File(file2Path); 

    BufferedReader br1 = new BufferedReader(new FileReader(file1)); 
    BufferedReader br2 = new BufferedReader(new FileReader(file2)); 

    String thisLine = null; 
    String thatLine = null; 

    List<String> list1 = new ArrayList<String>(); 
    List<String> list2 = new ArrayList<String>(); 

    while ((thisLine = br1.readLine()) != null) { 
     list1.add(thisLine); 
    } 
    while ((thatLine = br2.readLine()) != null) { 
     list2.add(thatLine); 
    } 

    br1.close(); 
    br2.close(); 

    return list1.equals(list2); 
} 
-2

, 아래의 코드를 비교하는 파일의 내용

public boolean compareTwoFiles(String file1Path, String file2Path){ 
     Path p1 = Paths.get(file1Path); 
     Path p1 = Paths.get(file1Path); 

try{ 
     List<String> listF1 = Files.readAllLines(p1); 
    List<String> listF2 = Files.readAllLines(p2); 
    return listF1.containsAll(listF2); 

     }catch(IOException ie) { 
      ie.getMessage(); 
     } 

    } 
+0

이것은 비효율적입니다 - 전체 파일을 메모리로 읽어들입니다. 또한 잘못된 - containsAll()은 순서가 동일한 지 확인하지 않습니다. –

관련 문제