There is a text file filled with 1's and 0's. I am trying to load one N_by_M matrix in Java with all data taken from that file. I do not know the dimensions of the matrix ahead of time because it depends on how much data the file has. What is guaranteed is that each line in the file contains the same number of characters. My code snippet works, but I feel awkward about it because:
- I am using a BufferedReader instance once only to calculate the number of rows and closing it and creating another instance only because I do not know how to rewind!
- I am using the second instance to read the actual data and load to the matrix.
- Within a loop, I am finding the column size. I need to find it only once. Yet, it is in a loop, finding it again and again which is redundant.
Please tell me how I could improve it by using BufferedReader only once and how to find the column only once.
char[][] areas;
String path = "C:\\test\\data.txt";
BufferedReader br = new BufferedReader(new FileReader(path));
String s;
int numRows=0, numColumns=0;
while((s = br.readLine()) != null) {
if(numColumns==0)
numColumns=s.length();
numRows++;
}
br.close();
areas = new char[numRows][];
br = new BufferedReader(new FileReader(path));
int i=0;
while((s = br.readLine()) != null) {
areas[i] = s.toCharArray();
i++;
}
br.close();