1

我有一堆 .txt 文件,我正在尝试阅读,但其中许多文件不会阅读。不会阅读的内容似乎以文本前的空行开头。例如,以下会引发 NoSuchElementException:

public static void main(String[] args) throws FileNotFoundException{
    Scanner input = new Scanner(new File("documentSets/med_doc_set/bmu409.shtml.txt"));
    System.out.println(input.next());
}

正在读取的文本文件以空行开头,然后是一些文本。我也尝试过使用 input.skip("[\\s]*") 跳过任何前导空格,但它会引发相同的错误。有没有办法解决这个问题?

编辑:托管在谷歌文档上的文件。如果您下载以在文本编辑器中查看,您可以看到它以空行开头。

4

3 回答 3

3

Scanner处理输入时,类型出奇地不一致。它吞下 I/O 异常——消费者应该明确地测试这些异常——所以它在通知读者错误方面是松懈的。但是在解码字符数据时类型是严格的 - 错误编码的文本或使用错误的编码将导致引发 an IOException,类型会迅速吞下。

此代码通过错误检查读取文本文件中的所有行:

  public static List<String> readAllLines(File file, Charset encoding)
      throws IOException {
    List<String> lines = new ArrayList<>();
    try (Scanner scanner = new Scanner(file, encoding.name())) {
      while (scanner.hasNextLine()) {
        lines.add(scanner.nextLine());
      }
      if (scanner.ioException() != null) {
        throw scanner.ioException();
      }
    }
    return lines;
  }

此代码读取行并将解码器无法理解的代码点转换为问号:

  public static List<String> readAllLinesSloppy(File file, Charset encoding)
      throws IOException {
    List<String> lines = new ArrayList<>();
    try (InputStream in = new FileInputStream(file);
        Reader reader = new InputStreamReader(in, encoding);
        Scanner scanner = new Scanner(reader)) {
      while (scanner.hasNextLine()) {
        lines.add(scanner.nextLine());
      }
      if (scanner.ioException() != null) {
        throw scanner.ioException();
      }
    }
    return lines;
  }

这两种方法都要求您明确提供编码,而不是依赖通常不是 Unicode 的默认编码(另请参阅标准常量。)

代码是 Java 7 语法,未经测试。

于 2012-09-03T08:07:17.417 回答
1

它以空行开头,您只打印代码中的第一行,将其更改为:

public static void main(String[] args) throws FileNotFoundException{
    Scanner input = new Scanner(new File("documentSets/med_doc_set/bmu409.shtml.txt"));
    while(input.hasNextLine()){
        System.out.println(input.nextLine());
    }
}
于 2012-09-02T20:38:10.590 回答
0

扫描仪读取所有单词或数字,直到行尾。此时您需要调用 nextLine()。如果您想避免出现异常,您需要调用其中一个 hasNextXxxx() 方法来确定是否可以读取该类型。

于 2012-09-02T20:39:27.810 回答