【问题标题】:Reading from file infinite loop in Java在Java中从文件无限循环中读取
【发布时间】:2017-01-24 20:34:01
【问题描述】:

谁能明白为什么这会导致我的 Java servlet 挂起?编译但 CPU 达到 100%,所以我假设某处存在无限循环..?

quotes.txt 只有 10 行。

String line = "";
try {

    String filePath = new File("").getAbsolutePath();
    filePath += "/quotes.txt";
    Scanner scan = new Scanner(filePath);

    int lines = 0;
    while (scan.hasNextLine()) {
        lines++;
    }

    Random random = new Random();
    int randomInt = random.nextInt(lines);

    for (int i = 0; i < randomInt; i++) {
     line = scan.nextLine();
    }

    scan.close();

    } catch (Exception e){
      line = e.getMessage();
   }

谢谢

【问题讨论】:

  • 你的 while 循环检查它是否有下一行,但从不读取下一行
  • while (scan.hasNextLine()) - 在此循环中,您从未从扫描仪读取数据。因此,即使只有一行,也将永远有“下一行”可用。
  • @A.A.第一个循环计算行数,以便第二个循环仅选择文件中实际存在的随机行数。
  • @David 啊,也许我误解了 .hasNextLine。我正在寻找“循环和计数行直到文件结束”效果
  • @StephenOrr 而不是Scanner 使用Files#readAllLines 方法。它返回一个List&lt;String&gt;

标签: java infinite-loop


【解决方案1】:

您好,您在扫描仪构造函数中传递字符串。 你需要使用

 Scanner sc = new Scanner(new File(filepath));

为什么如果您使用计数器来计算行数,如果您想从文件中读取,为什么还要随机使用 for 循环 你可以使用

 while(sc.hasNextLine()){
 line= sc.nextLine();}

这会给你最后一行。

EDIT 从文件中获取随机行。当您的光标在 while 循环中移动到文件末尾时

 int count=0;
 List<String> lines = new ArrayList<>();
 while(sc.hasNextLine()){
    line= sc.nextLine();
    lines.add(line);
    count++;
}
 Random rand = new Random();
 int n= rand.nextInt(count);
 String output = lines.get(n);

【讨论】:

  • 我正在尝试随机获取一行,而不是最后一行。
  • 你的循环是很好的扫描器构造器,你需要传递输入流,而你只是传递字符串。
【解决方案2】:

您的代码挂起,因为在第一个循环中未调用 scan.nextLine()。即使您实现它,第二个循环(for 循环)也会抛出异常,因为扫描仪没有来自文件的输入。

您可以通过重新初始化Scanner 对象来避免这种情况。

由于您想从文件中获取随机行(以任何顺序),我建议如下:

try {

    String filePath = new File("").getAbsolutePath();
    filePath += "/quotes.txt";

    List<String> listOfLines = Files.readAllLines(Paths.get(filePath), Charset.defaultCharset());

    Random random = new Random();
    int randomInt = random.nextInt(listOfLines.size());

    System.out.println(listOfLines.get(randomInt));

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

现在上面的代码将所有的行读入内存(这个方案显然不适用于大文件),之后就可以获取随机数并显示该行了。

你也可以看看this SO Question

【讨论】:

    【解决方案3】:

    HasNextLine 不会移动到下一个值,所以使用 nextLine 来移动它。如果你想使用它,你也可以将它分配给一个变量。

       ArrayList<String> a = new Arraylist<String>();
        while (scan.hasNextLine()) {
         a.add(scanner.nextLine());
        }
        Random random = new Random();
        int randomInt = random.nextInt(a.size());
        line = a.get(randomInt);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-06-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-10-27
      相关资源
      最近更新 更多