繁体   English   中英

在空白文件中使用两台扫描仪

[英]Using two scanners in file with blanks

我正在浏览一个文本行之间有空行的 .txt 文件。

我有一个扫描仪,它接收每一行并将其提供给第二个扫描仪,该扫描仪从该行中获取每个单词。

我遇到的问题是,如果我打了一个空行,第一个扫描仪将获得 null 输入,用于它的.nextLine()。

我怎样才能确保:

  1. 我还有更多文本(而不仅仅是空行),只需制作一个单独的 boolean 来检查它可能会更容易。

  2. 如果 boolean 检查正常,那么只需跳过那些空行并将实际包含文本的行中的文本传递给第二个扫描仪。

到目前为止,我的尝试是这样的:

Scanner one //scans each line from file
Scanner two //scans each word from scanner one

public boolean more() {
    if (two.more()) {
        return true;
    } else if (one.hasNext()) {
        two = new Scanner(one.nextLine());
        return this.more();
    } else {
        return false;
    }
}

public String getText() {
    String text = "";
    if(two.hasNext()) {
        text = two.next();
    } else {
        while(!one.hasNext()) {
            one.nextLine();
        }
        two = new Scanner(one.NextLine());
        text = two.next();
    }
    return text;
}

一个简单的解决方案是修剪从第一个 Scanner 获得的行,然后仅在第二个 Scanner 不为空时将其传递给第二个 Scanner。 例如:

import java.util.Scanner;

public class ScannerTest {
   private static final String TXT = "ScannerTest.txt";

   public static void main(String[] args) {
      Scanner outerScan = 
           new Scanner(ScannerTest.class.getResourceAsStream(TXT));
      while (outerScan.hasNextLine()) {
         String line = outerScan.nextLine().trim();
         if (!line.isEmpty()) {
            Scanner innerScan = new Scanner(line);
            while (innerScan.hasNext()) {
               String nextToken = innerScan.next();
               System.out.println("Token: " + nextToken);
            }
            innerScan.close();
         }
      }
      outerScan.close();
   }
}

在此文件上测试:ScannerTest.txt

Hello world

goodbye world

what the heck

Output:

Token: Hello
Token: world
Token: goodbye
Token: world
Token: what
Token: the
Token: heck

暂无
暂无

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

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