简体   繁体   中英

Skipping Predefined Lines in FileReader

I've been programming a text-based RPG game, and I'm trying to implement a save game feature. Everything is coded and works correctly.

It works by having a file called "slist" that holds the name of the savegame and the "session ID Number" . There is then a file for each savegame. The program scans this file to see if a savefile exists or not, then determines actions from there.

Note: I know this can be simplified a lot, but want to learn that on my own.

The problem I'm running into is that I want to be able to skip lines when reading from a file using FileReader. This is so users can share files with one another, and I can add comments for them at the top of the file (see below).

I've tried using Scanner.nextLine(), but it needs to be possible to insert a certain character anywhere in the file and have it skip the line following the character (see below).

private static String currentDir = new File("").getAbsolutePath();
private static File sessionList= new File(currentDir + "\\saves\\slist.dat"); //file that contains a list of all save files

private static void readSaveNames() throws FileNotFoundException {

Scanner saveNameReader = new Scanner(new FileReader(sessionList));

int idTemp;
String nameTemp;

while (saveNameReader.hasNext()) {

//   if line in file contains #, skip the line
nameTemp = saveNameReader.next();
idTemp = saveNameReader.nextInt();
saveNames.add(nameTemp);
sessionIDs.add(idTemp);
}
saveNameReader.close();
}

And the file it refers to would look something like this:

# ANY LINES WITH A # BEFORE THEM WILL BE IGNORED.
# To manually add additional save files,
# enter a new blank line and enter the
# SaveName and the SessionID.
# Example: ExampleGame 1234567890
GenericGame 1234567890
TestGame 0987654321
#skipreadingme 8284929322
JohnsGame 2718423422

Is there are way to do this, or would I have to get rid of any "comments" in the file and use a for loop to skip the top 5 lines?

My Java's a bit rusty, but...

while (saveNameReader.hasNext()) {

  nameTemp = saveNameReader.next();

  //   if line in file contains #, skip the line
  if (nameTemp.startsWith("#"))
  {
    saveNameReader.nextLine();
    continue;
  }

  idTemp = saveNameReader.nextInt();
  saveNames.add(nameTemp);
  sessionIDs.add(idTemp);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM