【问题标题】:Java scanner not starting from beginning of fileJava 扫描器未从文件开头开始
【发布时间】:2014-09-05 01:27:03
【问题描述】:

首先,这不是其他帖子的重复,因为在我的问题中,扫描程序类无法识别 .txt 文件的开头而不是结尾,而是从文件的大约 1/2 处开始。

这是我的代码:

package Program;

import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;

public class App {

public static void main(String[] args) throws FileNotFoundException {
    String filename = "C:\\Users\\vroy\\Programming\\Text documents\\P&P.txt";

    File textFile = new File(filename);

    Scanner reader = new Scanner(textFile);

    // int value = reader.nextInt();
    // System.out.println(value);

    while (reader.hasNextLine()) {
        String line = reader.nextLine();
        System.out.println(line);
    }

    reader.close();
}

}

这是我的程序正在读取的 .txt 文档:

http://www.goodreads.com/ebooks/download/1885.Pride_and_Prejudice?doc=2

我的程序开始打印从以下位置开始的文本行:“with the ill-judged offciousness...”

它应该从文档开始。

这是扫描仪类的问题吗?

【问题讨论】:

标签: java text java.util.scanner


【解决方案1】:

这是扫描仪类的问题吗?

没有。

我刚刚测试了您的代码。答案实际上很有趣——我假设您在 Eclipse 等 IDE 中运行此代码。 System.out.println() 打印到“控制台”。控制台有它显示的最大行数,并且由于您的文件很长,它不显示开头。

它正在遍历所有行。为了证明这一点,让它在打印一行时增加一个数字,例如:

int counter = 0;
while (reader.hasNextLine()) {
    String line = reader.nextLine();
    System.out.println(line);
    counter++;
}

您将看到该计数器正是文档中的行数。

【讨论】:

  • 但为什么它会在 netbeans ide 中从头开始显示所有内容?
  • 不同的 IDE 或不同的设置会将控制台限制为不同的行数。他的任何导入类(java.io.File 和 java.util.Scanner)没有理由不工作,除非他对它们进行反编译、编辑和重新编译(非常不可能)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-12-08
  • 1970-01-01
  • 2013-12-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多