在FileReader中跳过预定义的行

问题描述:

我一直在编写一个基于文本的RPG游戏,并且我试图实现一个保存游戏功能。一切都被编码并正常工作。在FileReader中跳过预定义的行

它的工作原理有一个名为“SLIST”文件保存游戏存档和“会话ID号”名称。每个游戏都有一个文件。程序扫描该文件以查看是否存在保存文件,然后从中确定操作。

注:我知道这可以简化很多,但要自己学习。

我遇到的问题是,我希望能够在使用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); 
} 
+0

直到你到达最后一个会话ID(2718423422)的作品。它读取名称,但不是ID号码。 – Aaron 2013-04-26 23:09:22

+1

2718423422对于Java int来说太大,因此抛出了java.util.InputMismatchException错误。最大整数值是2147483647.您将需要使用多头。 请参阅http://docs.oracle.com/javase/tutorial/java/nutsandbolts/datatypes.html对于Java原始类型限制 – 2013-04-26 23:31:28

+0

没有捕捉到 - 我随机输入了10个数字。我改变了sessionID有9个数字,所以它不应该再遇到这个错误。 – Aaron 2013-04-26 23:40:13