문제

I'm trying to read in from two files and store them in two separate arraylists. The files consist of words which are either alone on a line or multiple words on a line separated by commas. I read each file with the following code (not complete):

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

FileInputStream fis;
fis = new FileInputStream(fileName);

Scanner scan = new Scanner(fis);

while (scan.hasNextLine()) {
    Scanner input = new Scanner(scan.nextLine());
    input.useDelimiter(",");
    while (scan.hasNext()) {
        String md5 = scan.next();
        temp.add(md5);
    }
}
scan.close();    

return temp;

Each file contains almost 1 million words (I don't know the exact number), so I'm not entirely sure that the above code works correctly - but it seems to.

I now want to find out how many words are exclusive to the first file/arraylist. To do so I planned on using list1.removeAll(list2) and then checking the size of list1 - but for some reason this is not working. The code:

public static ArrayList differentWords(String fileName1, String fileName2) {
    ArrayList<String> file1 = readFile(fileName1);
    ArrayList<String> file2 = readFile(fileName2);

    file1.removeAll(file2);

    return file1;
}

My main method contains a few different calls and everything works fine until I reach the above code, which just causes the program to hang (in netbeans it's just "running").
Any idea why this is happening?

도움이 되었습니까?

해결책

You are not using input in

while (scan.hasNextLine()) {
  Scanner input = new Scanner(scan.nextLine());
  input.useDelimiter(",");
  while (scan.hasNext()) {
    String md5 = scan.next();
    temp.add(md5);
  }
}

I think you meant to do this:

while (scan.hasNextLine()) {
  Scanner input = new Scanner(scan.nextLine());
  input.useDelimiter(",");
  while (input.hasNext()) {
    String md5 = input.next();
    temp.add(md5);
  }
}

but that said you should look into String#split() that will probably save you some time:

while (scan.hasNextLine()) {
  String line = scan.nextLine();
  String[] tokens = line.split(",");
  for (String token: tokens) {
    temp.add(token);
  }
}

다른 팁

try this :

for(String s1 : file1){
    for(String s2 : file2){
        if(s1.equals(s2)){file1.remove(s1))}
    }
}
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top