为何在读取文件时扫描仪无法转到下一行?

时间:2018-10-25 08:44:53

标签: java file java.util.scanner file-handling

我正在使用以下代码读取文件:

Scanner fscanner = null;
try {
    fscanner = new Scanner(new File("spotify.txt"));
} catch (FileNotFoundException e) {

    e.printStackTrace();
}

while(fscanner.hasNextLine()) {
    String line = fscanner.nextLine();

    Scanner lineScanner = new Scanner(line);
    Album album = new Album();

    if(lineScanner.next().equals("CD")) {
        album.setComposers(lineScanner.next().replaceAll(",", "'s"));
        album.setAlbumName(lineScanner.useDelimiter(",").next().trim());
        album.setYear(lineScanner.next().trim());
        fscanner.nextLine();

        String c = album.getAlbumName();
        String a = album.getComposers();
        String y = album.getYear();

        System.out.println(a+" "+c+" "+y);

    }
    else if(lineScanner.next().equals("SONGS")) {
        ArrayList<String> songs = new ArrayList<String>();
        ArrayList<String> songDur = new ArrayList<String>();

        lineScanner.nextInt();

        songs.add(lineScanner.useDelimiter(",").next());
        songDur.add(lineScanner.next());

        album.setSongs(songs);
        album.setSongDurations(songDur);

        for(int i=0, j=0;i<songs.size() && j<songDur.size();i++, j++)
            System.out.println("SONG "+i+" "+songs.get(i).toString()+ " "+songDur.get(j).toString());

        System.out.println(album.showSongs());
        System.out.println(album.showSongDurations());

    }
    else if(lineScanner.next().equals("ADD")) {
        Adds adds = new Adds();

        adds.setCompanyName(lineScanner.useDelimiter(",").next().trim());
        adds.setDuration(lineScanner.next());
    }
}

文件看起来像这样:

CDS
CD U2, Songs of Innocence, 2014
SONG 1, The Miracle, 4:15
SONG 2, Every Breaking Wave, 4:12
SONG 3, California, 4:00
SONG 4, Song for Someone, 3:47
CD Coldplay, Parachutes, 2000
SONG 1, Don’t Panic, 2:17
SONG 2, Shiver, 5:00
SONG 3, Spies, 5:19
SONG 4, Sparks, 3:47
SONG 5, Yellow, 4:27
CD ImagineDragons, Night Visions, 2015
SONG 1, Demons, 3:14
SONG 2, Monster, 2:57
ADDS
ADD ING Bank, 0:20
ADD Bol.com, 0:15
ADD Albert Heijn, 0:30
ADD Specsavers, 0:15
ADD Kruidvat, 0:10
ADD MediaMarkt.nl, 0:20

问题是我在NoSuchElementException行得到else if(lineScanner.next().equals("SONGS"))

如果我同时删除了两个else-ifs,那么当代码实际执行到下一行时,我根本不知道为什么会这样。

它提供的输出与预期的完全一样,但是当我介绍那些else-ifs时却没有。

我该如何解决?

3 个答案:

答案 0 :(得分:1)

在第一行上,您将读取第一个令牌并检查它是否等于CD;否则,您将尝试从同一行读取另一个令牌,以检查它是否等于SONGS,这将在第一行引发错误,因为没有更多的令牌可读取那条线。

您将要在if / else if之前将行的第一个标记读取到变量中,并在您的条件中引用该变量,以便它们都对照行的第一个标记进行检查。

请注意,我会避免使用两个不同的扫描仪;如果我没记错的话,您在调用CD时错误地跳过了fscanner.nextLine();分支中的一行,这仅在您在各处使用相同的扫描仪时才有用(丢弃未使用的剩余部分)线)。在这种情况下,nextLine调用应放在if / else if之后,以避免重复。

答案 1 :(得分:0)

首先检查您的lineScanner是否还有要剖析的元素。然后,使用新变量引用lineScanner.next()的返回变量,这样就不必每次if-else检查时都调用lineScanner.next(),因为此方法每次调用都会跳到下一个单词。不过不是很明显。

Scanner fscanner = null;
    try {
        fscanner = new Scanner(new File("src/spotify.txt"));
    } catch (FileNotFoundException e) {

        e.printStackTrace();
    }

    while(fscanner.hasNextLine()) {
        String line = fscanner.nextLine();

        Scanner lineScanner = new Scanner(line);

        while(lineScanner.hasNext()){
            //Trim the word
            String word = lineScanner.next().trim();
            System.out.println(word);
        }
    }
    //Do not forget to close it
    fscanner.close();

答案 2 :(得分:0)

@Arron给了你原因。

现在也许这可能有助于我相信它比扫描仪更快,更好

int count = Files.lines(Paths.get(text_File_Location)).count(); //count number of lines in text file without any loop

 Path path = Paths.get(*text_File_Location, Name or URL*);

               for (int i = 0; i < count; i++) 
               {   
                    //It read exactly what we need
                    String line = Files.readAllLines(path).get(i);

                    //lets say u have data in text file in this format
                    //SONG,MUSIC,YEAR   Separated by comma


                    String everything[] = line.split(",");
                    String song = everything[0];
                    String music = everything[1];
                    String year = everything[2];

               }