java - 从文件中读取整数值 (Java)

标签 java file file-io inputstream java.util.scanner

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

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

enter image description here

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

我的文件阅读代码在下面,选择要阅读的部分工作正常 - 例如。如果我通过执行以下操作传入 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");
                }


    }

最佳答案

扫描仪是一个很好的答案。为了更接近您所拥有的,请使用 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);
}

关于java - 从文件中读取整数值 (Java),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17575667/

相关文章:

java - 如何制作在 Lollipop 设备上设计的 PreferenceActivity Material ?

java - 带有 Gradle 的 Tomcat 上的 Spring REST 服务

python - 如何将多维数组写入文本文件?

ruby - 未定义方法 `split' 为 nil :NilClass (NoMethodError) for an array

java hashMap并发修改异常

linux - Linux下文件格式的改变

android - RecyclerView 的第一项丢失

file - Spark 分区/集群执行

JavaScript 文件到 byte[]

java - 应用程序无法发出获取请求