我一直在编写基于文本的 RPG 游戏,并且正在尝试实现保存游戏功能。一切都已编码并正常工作。
它的工作原理是通过一个名为“slist”的文件来保存保存游戏的名称和“ session 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);
}
关于java - 在 FileReader 中跳过预定义行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16246198/