使用扫描仪和文本文件获取一行中的某个字符串

时间:2014-09-28 11:29:13

标签: java

所以我希望扫描仪分析文本文件的每一行,并在x个单词后停止,在这种情况下x = 3.

我的代码看起来像这样:

    scannerName.nextLine();
    scannerName.next();
    scannerName.next();
    scannerName.next();

嗯,这里的问题是nextLine()使扫描程序超过当前行AS WELL AS返回一个字符串。所以如果我调用next(),那么就会找到下一行的下一个字符串(右边?)。

有没有办法做我要问的事情?

谢谢

2 个答案:

答案 0 :(得分:1)

请尝试以下代码: - while(scannerName扫描名称.hasNext()!= null) {

scannerName.next(); //Returns the 1st word in the line
scannerName.next(); //Returns the 2nd word in the line
scannerName.next(); //Returns the 3rd word in the line
//Analyze the word.
scannerName.nextLine();

}

答案 1 :(得分:1)

您的问题不是那么精确,但我有一个从txt文件中读取的解决方案:

Scanner scan = null;
    try {
        scan = new Scanner(new File("fileName.txt"));                       
    } catch (FileNotFoundException ex) {
        System.out.println("FileNotFoundException: " + ex.getMessage());
    } catch (Exception e) {
        System.out.println("Exception: " + e.getMessage());
    }

    int wordsRead = 0;
    int wordsToRead = 3;                               //== You can change this, to what you want...
    boolean keepReading = true;

    while (scan.hasNext() && keepReading) {
        String currentString = scan.nextLine();        //== Save the entire line in a String-object 
        for (String word : currentString.split(" ")) {
            System.out.println(word);                  //== Iterates over every single word - ACCESS TO EVERY WORD HAPPENS HERE
            wordsRead++;
            if (wordsRead == wordsToRead) {
                keepReading = false;                   //== makes sure the while-loop will stop looping
                break;                                 //== breaks when your predefined limit is is reached
            } //== if-end
        } //== for-end
    } //== while-end

如果您有任何疑问,请与我联系: - )