java.util.NoSuchElementException:从文件中读取单词

时间:2015-01-06 20:51:58

标签: java java.util.scanner

这个简单的java程序出了什么问题?

我正在尝试从文件中读取单词并获得以下异常:

complication
dilemma
lavender
issue
happy
weird
Exception in thread "main" java.util.NoSuchElementException
    at java.util.Scanner.throwFor(Scanner.java:907)
    at java.util.Scanner.next(Scanner.java:1416)
    at com.recrawl.util.ReadWordsTextfile.readWordsFromTextFile(ReadWordsTextfile.java:32)
    at com.recrawl.util.ReadWordsTextfile.main(ReadWordsTextfile.java:13)

正如你所看到的那样,我得到了一些例外。我使用以下代码:

public static void main(String[] args) {
    String path = "Word_and_phrases";
    ReadWordsTextfile r = new ReadWordsTextfile();
    r.readWordsFromTextFile(path);  
}

public ArrayList<String> readWordsFromTextFile(String path) {
    ArrayList<String> resultList = new ArrayList<String>();

    FileInputStream fileIn = null;
    try {
        fileIn = new FileInputStream(path);
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    }
    Scanner scan = new Scanner(fileIn);
    while(scan.hasNextLine()) {
        String word = scan.next();
        word = word.replace(",", "");
        System.out.println(word);
        resultList.add(word);
    }
    scan.close();
    System.out.println(resultList.toString());
    return resultList;
}

我非常感谢你的回答!

更新

txt文件的内容如下所示:

complication, dilemma, lavender, issue, happy, weird

第32行是:

    String word = scan.next();

1 个答案:

答案 0 :(得分:2)

使用:

while(scan.hasNext())

而不是:

while(scan.hasNextLine())
实施

hasNext以与next()一起使用hasNextLine,同时使用nextLine()