2016-12-16 67 views
1

從文件讀取時遇到一些問題。我試圖從一個文本文件讀取並讀取和寫入一個矩陣的字符。問題是我得到了一個IndexOutOfBounds異常,我不知道爲什麼會發生這種情況。從Java讀取文件時出現奇怪的行爲

這是我的代碼:

public static char[][] readTxt(String args[]) { 
    String file = args[0]; 
    try { 
     FileReader fr = new FileReader(file); 
     BufferedReader br = new BufferedReader(fr); 

     String line = br.readLine(); 

     //counter 
     int counter = 0; 

     String[] tam = line.split(","); 

     char[][] maze = new char[tam.length][tam.length]; 

     while (line != null) { 
      String[] values = line.split(","); 

      for (int i = 0; i < values.length; i++) { 
       maze[counter][i] = values[i].charAt(0); 
      } 
      counter++; 
      line = br.readLine(); 
     } 
     br.close(); 
     return maze; 
    } catch (Exception e) { 
     System.out.println("Exception reading file " + file + ": " + e); 
    } 
    return null; 
} 

它拋出IndexOutOfBounds在char[][] maze = new char[tam.length][tam.length];

我的輸入是這樣的:

%,%,%,%,%,%,%,%,%,%,% %,C, , , ,C, , ,C, ,% %,%,%, , , ,%,%,%,%,% %,C, , , ,C, , , , ,% %, , , , , , , , , ,% %, , , , , , , , , ,% %, , , , , , , , , ,% %, , , , , , , , , ,% %, , , , , , , , , ,% %, , , , , , , , , ,% %,%,%,%,%,%,%,%,%,%,%

我也試圖將其更改爲:

char[][] maze = new char[tam.length+1][tam.length+1]; 

現在它可以工作,但我不知道爲什麼。有任何想法嗎?

PD:當我印刷矩陣時,我看到了一些奇怪的東西。它看起來像它在我的矩陣的右側印一些空白字符,但在我的輸入文件我不寫任何空白字符:(

my matrix in java

任何想法?

+3

您的第一行已被閱讀。 – Bhoot

+0

'linea'從哪裏來? –

+1

文件中的數據實際上是什麼? –

回答

1

是您的假設,即你總是有儘可能多的行,你行是否正確?

我不會呼叫相互地方readLine相隔那麼遠中有條目。你知道嗎,你可以寫流,並與nio.Files也相似的地方?

您的代碼有些不同,無需檢查計數器:

Character[][] maze = Files.lines(Paths.get(stringPathOrUri)) 
     .map(s -> s.split(",")) 
     .map(strings -> Stream.of(strings) 
          .map(s -> s.charAt(0)) // better: insert your transformation function here 
          .toArray(Character[]::new)) 
     .toArray(Character[][]::new); 

這仍有待提高,但你可能會得到的想法。