我正在编写一个程序,读取两个文本文件并找出差异 但由于某种原因,我无法打印结果集。我检查了很多次还是没有找到原因,希望大家能帮帮我。这是代码。
问题出现在每个打印集的位置。
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);
}
}
最佳答案
你的问题是范围。您在 try block 内定义该集合,但随后尝试从该 block 外部访问它。您必须在要使用该变量的同一范围内定义所有变量。
将 uniqueUsers 的定义移至 try block 之前。
*编辑以回应您的评论。
您正在从同一输入流读取两次。第二个 while 循环应该从 inputStream2 读取。
关于java - 无法在Java中打印出集合,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21396187/