[英]Reading a 2d array from a file in java
我有一個32x32大小的文本文件。 例如前兩行:
11111111111111111111111111111111
11111111111111111111111111111000
...
我想讀取此文件並將其存儲在2D數組中。 我有以下Java代碼,但無法完全弄清楚如何讀取文件數據。 我想我需要兩個嵌套的for循環?
public static int[][] readFile(){
BufferedReader br = null;
int[][] matrix = new int[32][32];
try {
String thisLine;
int count = 0;
br = new BufferedReader(new FileReader("C:\\input.txt"));
while ((thisLine = br.readLine()) != null) {
//two nested for loops here? not sure how to actually read the data
count++;
}
return matrix;
}
catch (IOException e) {
e.printStackTrace();
}
finally {
try {
if (br != null)br.close();
}
catch (IOException ex)
{
ex.printStackTrace();
}
}
return matrix;
}
假設文件中的每一行都是一行,並且對於每一行,一個字符就是一個條目:
// ...
int i,j;
i = 0;
while((thisLine = br.readLine()) != null) {
for(j = 0; j < thisLine.lenght(); j++) {
matrix[i][j] = Character.getNumericValue(thisLine.charAt(j));
}
i++;
}
// ...
這只是一個起點……可能會有許多更有效,更干凈的方法來執行此操作,但是現在您有了主意。
您只需要再一個循環,因為您已經擁有的while循環將充當外部循環。
while ((thisLine = br.readLine()) != null) {
for(int i = 0; i < thisLine.length(); i++){
matrix[count][i] = Character.getNumericValue(thisLine.charAt(i));;
}
count++;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.