2013-07-10 91 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; 
    } 
} 

你還需要一些代碼在那裏處理錯誤,包括文件過早結束。