1

我正在为我的 Android 游戏开发一个简单的关卡编辑器。我已经使用 swing 编写了 GUI(绘制网格)。您单击要放置瓷砖的方块,它会改变颜色。完成后,将所有内容写入文件。

我的文件包含以下内容(这只是一个示例):

在此处输入图像描述

我使用星号来确定正在阅读的级别编号,并使用连字符来告诉读者停止阅读。

我的文件读取代码如下,例如,选择要读取的部分可以正常工作。如果我通过执行以下操作传入 2:

readFile(2);

然后它打印第二部分中的所有字符

我无法弄清楚的是,一旦我到达“起点”点,我如何实际将数字读取为整数不是单个字符?

代码

    public void readFile(int level){

        try {
                    //What ever the file path is.
                    File levelFile = new File("C:/Temp/levels.txt");
                    FileInputStream fis = new FileInputStream(levelFile);
                    InputStreamReader isr = new InputStreamReader(fis);    
                    Reader r = new BufferedReader(isr);
                    int charTest;

                    //Position the reader to the relevant level (Levels are separated by asterisks)
                    for (int x =0;x<level;x++){
                    //Get to the relevant asterisk
                    while ((charTest = fis.read()) != 42){
                     }
                    }
                    //Now we are at the correct read position, keep reading until we hit a '-' char
                    //Which indicates 'end of level information'
                    while ((charTest = fis.read()) != 45){

                    System.out.print((char)charTest);   
                    }

                    //All done - so close the file
                    r.close();
                } catch (IOException e) {

                    System.err.println("Problem reading the file levels.txt");
                }


    }
4

4 回答 4

2

扫描仪是一个很好的答案。为了更接近您所拥有的,请使用 BufferedReader 读取整行(而不是一次读取一个字符)并使用 Integer.parseInt 从 String 转换为 Integer:

// get to starting position
BufferedReader r = new BufferedReader(isr);
...
String line = null;
while (!(line = reader.readLine()).equals("-"))
{
  int number = Integer.parseInt(line);
}
于 2013-07-10T16:24:14.597 回答
1

如果你使用BufferedReader而不是Reader接口,你可以调用r.readLine(). 然后你可以简单地使用Integer.valueOf(String)or Integer.parseInt(String)

于 2013-07-10T16:24:10.540 回答
1

也许您应该考虑使用readLinewhich 将所有字符放在行尾。

这部分:

for (int x =0;x<level;x++){
    //Get to the relevant asterisk
    while ((charTest = fis.read()) != 42){
    }
}

可以改成这样:

for (int x =0;x<level;x++){
    //Get to the relevant asterisk
    while ((strTest = fis.readLine()) != null) {
        if (strTest.startsWith('*')) {
             break;
        }
    }
}

然后,读取另一个循环的值:

for (;;) {
    strTest = fls.readLine();
    if (strTest != null && !strTest.startsWith('-')) {
        int value = Integer.parseInt(strTest);
        // ... you have to store it somewhere
    } else {
        break;
    }
}

您还需要一些代码来处理错误,包括文件过早结束。

于 2013-07-10T16:24:32.393 回答
0

我认为你应该看看 Java 中的 Scanner API。你可以看看他们的教程

于 2013-07-10T16:17:51.630 回答