0

I have a text file that is 32x32 in size. For example first two lines:

11111111111111111111111111111111
11111111111111111111111111111000
...

I want to read and store this file in a 2D array. I have the following java code, but can't exactly figure out how to read the file data. I guess I would need two nested for loops?

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;
}
1
  • 2
    That's simple : how do you convert a String of digits into an array of integers ? Commented Sep 25, 2014 at 17:53

2 Answers 2

3

Assuming that each line in your file is a row, and, for each row, a character is an entry:

// ...
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++;
}
// ...

This is just a starting point... there may be many more efficient and clean ways to do this, but now you have the idea.

Sign up to request clarification or add additional context in comments.

Comments

1

You only need one more loop, since the while loop you already have is functioning as the outer loop.

while ((thisLine = br.readLine()) != null) {
    for(int i = 0; i < thisLine.length(); i++){
        matrix[count][i] = Character.getNumericValue(thisLine.charAt(i));;
    }

count++;
}

2 Comments

Identical to my answer ;)
Got it thanks... And to write the 2D array back to file I just change it from BufferedReader to BufferedWriter?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.