2013-07-10 93 views
1

我正在为Android游戏设计一个简单的关卡编辑器。我用swing编写了GUI(绘制网格)。你点击你想放置一个瓷砖的方块,它会改变颜色。完成后,您将所有内容写入文件。读取文件中的整数值(Java)

我的文件包含类似下面的(这只是一个例子):

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


    } 

回答

2

扫描仪的一个很好的答案。为了保持接近你所拥有的,使用BufferedReader读取整行(而不是读取一个字符时),并以的Integer.parseInt从字符串转换为整数:

// get to starting position 
BufferedReader r = new BufferedReader(isr); 
... 
String line = null; 
while (!(line = reader.readLine()).equals("-")) 
{ 
    int number = Integer.parseInt(line); 
} 
+0

谢谢!这工作很好:-) – Zippy

0

我想你应该有一下Java中的扫描仪API。 你可以看看他们的tutorial

1

如果使用BufferedReader而不是Reader界面,你可以调用r.readLine()。那么你可以简单地使用Integer.valueOf(String)Integer.parseInt(String)

1

也许你应该考虑使用readLine这把所有的字符放到行尾。

这一部分:

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

你还需要一些代码在那里处理错误,包括文件过早结束。