I need to create an array of objects to save the records from files. I don't know about the size of an array. For that I have to find the number of lines in a file first. Using the number of lines, size of an array can be determined. Now I need to read the file again from the beginning to store records from the file in array object. This is where I am struggling. I don't know how to implement in order to read the file again from the beginning. Please advise.
/**
* Loads the game records from a text file.
* A GameRecord array is constructed to store all the game records.
* The size of the GameRecord array should be the same as the number of non-empty records in the text file.
* The GameRecord array contains no null/empty entries.
*
* @param reader The java.io.Reader object that points to the text file to be read.
* @return A GameRecord array containing all the game records read from the text file.
*/
public GameRecord[] loadGameRecord(java.io.Reader reader) {
// write your code after this line
String[] parts;
GameRecord[] gameRecord = null;
FileReader fileReader = (FileReader) reader;
java.io.BufferedReader bufferedReader = new java.io.BufferedReader(fileReader);
try {
int linenumber = 0;
String sCurrentLine;
while ((sCurrentLine = bufferedReader.readLine()) != null){
System.out.println(sCurrentLine);
linenumber++;
}
gameRecord = new GameRecord[linenumber]; //creating a space for total no Of lines
//How to read the file from the beginning again, and why I am getting bufferedReader.readLine()) as null
bufferedReader = new java.io.BufferedReader(fileReader);
while ((sCurrentLine = bufferedReader.readLine()) != null){
System.out.println(sCurrentLine);
parts = sCurrentLine.split("\t");
gameRecord[i] = new GameRecord(parts[0], Integer.parseInt(parts[1]),Integer.parseInt(parts[2]));
}
}catch (IOException exe){
System.err.println("IOException: " + exe.getMessage());
exe.printStackTrace();
}finally{
try {
if (bufferedReader!=null)
bufferedReader.close();
if (fileReader!=null)
fileReader.close();
}catch(IOException exe) {
System.err.println("IOException: " + exe.getMessage());
}
}
return gameRecord;
}
Note: I will get the reference to a file as an argument. Reader class has been used. Can I use this reference for FileInputStream?