使用Scanner读取文件Java时的无限循环

时间:2014-12-04 23:31:10

标签: java

所以我试图解析可能是

形式的文本文件
words words words werdz words

words
words
words
words
words

因此,我决定使用Scanner而不是BufferedReader,而且我对使用Scanner的经验不足。我正在尝试读取文件并保存到Collection。这是主要代码和补充方法。

主:

public static void main(String[] args) throws IOException {

        LinkedList<String> unmodDict = readDict(new File(args[0]));
        String[] unsorted = readUnsorted(new File(args[1]));

        ...

} 

readDict()

public static LinkedList<String> readDict(File file) throws IOException {
        //BufferedReader reader = new BufferedReader(new FileReader(file));
        Scanner s = new Scanner(new FileReader(file));
        String line = null;
        LinkedList<String> ll = new LinkedList<>();
        int count = 0;
        while(s.hasNext()) {
            ll.add(s.next());
        }
        // this loop seems to run finitely.
        s.close();
        return ll;
    }

readUnsorted()

public static String[] readUnsorted(File file) throws IOException {
        //BufferedReader reader = new BufferedReader(new FileReader(file));
        Scanner reader = new Scanner(new FileReader(file));
        int count = 0;
        while (reader.hasNext()) {
            count++;
        }
        reader.close();
        // The above loop is running infinitely.

        Scanner reader2 = new Scanner(new FileReader(file));
        String line2 = null;
        String[] unsortedWerdz = new String[count];
        int i = 0;
        while (reader2.hasNext()) {
            unsortedWerdz[i] = reader2.next();
            i++;
        }
        reader2.close();

        return unsortedWerdz;
    }

由于某种原因,readUnsorted方法中的第一个while循环无限运行但我无法理解为什么因为readDict方法中的第一个循环似乎运行正常。有人可以告诉我该做什么吗?

由于

1 个答案:

答案 0 :(得分:1)

它永远运行,因为您检查是否有下一个String可用,但您没有检索它! 你需要通过next()这样得到它:

while (reader.hasNext()) {
            reader.next();
            count++;
        }

否则Scanner将始终指向它所读取的相同(第一个)元素并始终报告:Yes, there's another token in here!