2014-01-28 4 views
0

Я пишу программу, которая читает в двух текстовых файлах и обнаруживает различия , но по какой-то причине я не могу напечатать результирующий набор. Я много раз проверял и все еще не мог найти причину, и я надеюсь, что вы, ребята, можете мне помочь. вот код.Не удается распечатать набор в Java

проблема возникает при каждом печатать набор.

import java.io.*; 
    import java.util.*; 

    public class PartOne { 


    public static void readFileAtPath(String filePathOne, String filePathTwo) { 
     // Lets make sure the file path is not empty or null 
     if (filePathOne == null || filePathOne.isEmpty()) { 
      System.out.println("Invalid File Path"); 
      return; 
     } 

     if (filePathTwo == null || filePathTwo.isEmpty()) { 
      System.out.println("Invalid File Path"); 
      return; 
     } 

     Set<String> newUser = new HashSet<String>(); 
     Set<String> oldUser = new HashSet<String>(); 

     BufferedReader inputStream = null; 
     BufferedReader inputStream2 = null; 
     // We need a try catch block so we can handle any potential IO errors 
     try { 
      // Try block so we can use ‘finally’ and close BufferedReader 
      try { 
       inputStream = new BufferedReader(new FileReader(filePathOne)); 
       inputStream2 = new BufferedReader(new FileReader(filePathTwo)); 

       String lineContent = null; 
       String lineContent2 = null; 

       // Loop will iterate over each line within the file. 
       // It will stop when no new lines are found. 
       while ((lineContent = inputStream.readLine()) != null) { 
        // Here we have the content of each line. 
        // For now, I will print the content of the line. 
        // System.out.println("Found the line: " + lineContent); 
        oldUser.add(lineContent); 
       } 

       while ((lineContent2 = inputStream.readLine()) != null) { 
        newUser.add(lineContent2); 
       } 

       Set<String> uniqueUsers = new HashSet<String>(newUser); 
       uniqueUsers.removeAll(oldUser); 

      } 
      // Make sure we close the buffered reader. 
      finally { 
       if (inputStream != null) 
        inputStream.close(); 
       if (inputStream2 != null) 
        inputStream2.close(); 
      } 


      for (String temp : uniqueUsers) { 
       System.out.println(temp); 
      } 

     } catch (IOException e) { 
      e.printStackTrace(); 
     } 
    }// end of method 

    public static void main(String[] args) { 
     String filePath2 = "userListNew.txt"; 
     String filePath = "userListOld.txt"; 
     readFileAtPath(filePath, filePath2); 

    } 
} 
+1

Попробуйте отладки приложения. –

+0

Что говорит об ошибке? – Prince

ответ

5

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

Переместите определение uniqueUsers перед блоком try.

* Редактировать в ответ на ваши комментарии.

Вы читаете один и тот же поток ввода дважды. Второй цикл while должен считываться из inputStream2.

+0

+1 хороший улов! : D – Prince

+0

спасибо! и теперь у меня другая проблема. Он успешно выполнил и выполнил. но его ничего не печатают. он должен распечатать разницу двух наборов. – Samson

+0

@Samson Я обновил свой ответ – Dodd10x

0

Попробуйте

try { 
    // Try block so we can use ‘finally’ and close BufferedReader 
    try { 
     inputStream = new BufferedReader(new FileReader(filePathOne)); 
     inputStream2 = new BufferedReader(new FileReader(filePathTwo)); 

     String lineContent = null; 
     String lineContent2 = null; 

     // Loop will iterate over each line within the file. 
     // It will stop when no new lines are found. 
     while ((lineContent = inputStream.readLine()) != null) { 
      // Here we have the content of each line. 
      // For now, I will print the content of the line. 
      // System.out.println("Found the line: " + lineContent); 
      oldUser.add(lineContent); 
     } 

     while ((lineContent2 = inputStream.readLine()) != null) { 
      newUser.add(lineContent2); 
     } 

     Set<String> uniqueUsers = new HashSet<String>(newUser); 
     uniqueUsers.removeAll(oldUser); 

     for (String temp : uniqueUsers) { 
     System.out.println(temp); 
     } 

    } 
    // Make sure we close the buffered reader. 
    finally { 
     if (inputStream != null) 
      inputStream.close(); 
     if (inputStream2 != null) 
      inputStream2.close(); 
    }   

} catch (IOException e) { 
    e.printStackTrace(); 
} 
Смежные вопросы