簡體   English   中英

在FileReader中跳過預定義的行

[英]Skipping Predefined Lines in FileReader

我一直在編寫基於文本的RPG游戲,並且正在嘗試實現保存游戲功能。 一切都經過編碼,可以正常工作。

它通過具有一個名為“ slist”的文件來工作,該文件包含savegame名稱“ session ID Number” 然后,每個保存游戲都有一個文件。 程序掃描該文件以查看是否存在保存文件,然后從那里確定操作。

注意:我知道這可以簡化很多,但是我想自己學習。

我遇到的問題是,我希望能夠在使用FileReader從文件讀取時跳過行。 這樣,用戶可以彼此共享文件,並且我可以在文件頂部為他們添加注釋(請參見下文)。

我試過使用Scanner.nextLine(),但是有必要在文件中的任何位置插入某個字符,並使其跳過字符后的行(請參見下文)。

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();
}

它引用的文件看起來像這樣:

# 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

有沒有辦法做到這一點,還是我必須擺脫文件中的任何“注釋”並使用for循環跳過前5行?

我的Java有點生銹,但是...

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);
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM