2013-07-10 5 views
1

나는 안드로이드 게임을위한 간단한 레벨 편집기를 만들고있다. 스윙을 사용하여 GUI (그리드 그리기)를 작성했습니다. 타일을 배치하려는 사각형을 클릭하면 색상이 바뀝니다. 일단 끝나면 모든 것을 파일에 씁니다.파일에서 정수 값 읽기 (Java)

enter image description here

내가 읽기를 중지 독자에게 읽는 수준 번호와 하이픈을 결정하기 위해 별표를 사용

내 파일 (이것은 단지 예입니다)는 다음과 같이 구성 .

내 파일 읽기 코드은 아래에서 읽을 부분을 선택하면됩니다. 예를 들어. 내가 수행하여 2 통과하면 다음

readFile(2); 

그럼 내가 '시작했으면 내가 알아낼 수없는 것을 제 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

스캐너는 좋은 답변입니다. 정수를 문자열로 변환하고있는 Integer.parseInt (대신 한 번에 하나 개의 문자를 읽는) 전체 라인을 읽을의 BufferedReader를 사용하여, 당신은 무엇을 가까이 유지하려면

// 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

나는 당신이 자바의 스캐너 API에서 봐한다고 생각합니다. 당신이 BufferedReader 아닌 Reader 인터페이스를 사용하는 경우 당신은 자신의 tutorial

1

에 모습을 가질 수 있습니다, 당신은 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; 
    } 
} 

을 파일의 조기 종료를 포함하여 오류를 처리합니다.