简体   繁体   English

Java从文本文件读取

[英]Java reading from Text file

I'm trying to read from text file and printout only unrepeated lines using list. 我正在尝试从文本文件读取并使用列表仅打印出未重复的行。

File file = new File("E:/......Names.txt");
List<String> names = new ArrayList<String>();

Scanner scan = new Scanner(file);
int j=1;

while(scan.hasNextLine() && j!=100 ){   
  if(!names.contains(scan.nextLine()))
    names.add(scan.nextLine());

  System.out.println(names);
  j++; 
}
scan.close();

Instead of calling scan.nextLine() twice, you should store the value in a variable: 您应该将值存储在变量中,而不是两次调用scan.nextLine()

String name = scan.nextLine();
if (!names.contains(name)) {
  names.add(name);

  // ...
}

Otherwise, you get a different value each time you call scan.nextLine() , so the value you check with contains is different to the one you add . 否则,每次调用scan.nextLine()时,您将获得一个不同的值,因此,您用来检查contains值不同于您add

However, it's simply easier to use a Set<String> , which guarantees not to allow duplicates: 但是,使用Set<String>更简单,因为它保证不允许重复:

Set<String> names = new LinkedHashSet<>();
// ...
while (scan.hasNextLine() && names.size() < 100) {
  if (names.add(scan.nextLine()) {
    // Only runs if it wasn't there before.
  }
}

You are trying to deal with the same line, but you deal with different ones: 您尝试处理同一行,但处理不同的行:

if(!names.contains(scan.nextLine())) //this reads a line
  names.add(scan.nextLine()); //but this reads another line!

Change it do this: 更改它,执行以下操作:

while(scan.hasNextLine() && j!=100 ){   
  String nextLine = scan.nextLine();
  if(!names.contains(nextLine)){
    names.add(nextLine);
  }
  //...

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM