如何从File读入2d char数组

时间:2015-04-19 17:09:58

标签: java arrays

我试图弄清楚如何读取这样的txt:

12  
12  
WWWWWWWWWWWW   
W3000000000W  
W0000000000W  
W0000000000W   
W0000000000W  
W0000000000W  
W0000000040W  
W0000000000W  
W0000000000W  
W0000000000W  
W0000000000W  
WWWWWWWWWWWW  

进入String[][];

前两行是String[][]的大小。 这是代码

  

线程中的异常" AWT-EventQueue-0" java.lang.ArrayIndexOutOfBoundsException:1 at map [i] [j] = temp [j] .toString();

public String[][] read() throws IOException{
    BufferedReader br = new BufferedReader(new FileReader("D:/College/Java Eclipse/Map.txt"));   
    String line = " ";


    int columnCount = Integer.parseInt(br.readLine());
    int rowCount = Integer.parseInt(br.readLine()); 

    String[] temp;
    String[][] map = new String[rowCount][columnCount];

    while ((line = br.readLine())!= null){ 
        temp = line.split("\\s+"); 

        for(int i = 0; i<rowCount; i++) {
            for (int j = 0; j<columnCount; j++) {    
                map[i][j] = temp[j].toString();
            }
        }

    }
    br.close();
    return map;

}

我无法弄清楚有什么问题?

1 个答案:

答案 0 :(得分:2)

您的正则表达式 line.split("\\s+")正在返回单个String并且您正在循环,就像它返回一个包含12个元素的数组(在您的情况下);无论如何,你要一次又一次地替换所有的值,因为你是在第一个for循环之外阅读。

尝试这样的事情:

public static String[][] read() throws IOException {
  BufferedReader br = new BufferedReader(new FileReader("D:/College/Java Eclipse/Map.txt"));
  int columnCount = Integer.parseInt(br.readLine());
  int rowCount = Integer.parseInt(br.readLine());
  String[][] map = new String[rowCount][columnCount];

  for (int i = 0; i < rowCount; i++) {
    String line = br.readLine();

    for (int j = 0; j < columnCount; j++) {
      map[i][j] = String.valueOf(line.charAt(j));
    }
  }
  br.close();
  //System.out.println(Arrays.deepToString(map));
  return map;
}