I am completely stumped in trying to read from a file and adding it to an array. So what I tried to implement was reading the line into a temporary String array, then adding the temporary value to the main array,
This is the contents of the text file I would like to split into an array line by line. So that i could take each line, do calculations with the numbers and format an output.
Mildred Bush 45 65 45 67 65 into [[Mildred Bush],[45],[65],[67],[65]]
Fred Snooks 23 43 54 23 76 etc.
Morvern Callar 65 45 34 87 76 etc.
Colin Powell 34 54 99 67 87
Tony Blair 67 76 54 22 12
Peter Gregor 99 99 99 99 99
However, when run whats in the main array is [Mildred, Fred, Morvern, Colin, Tony, Peter]. So meaning that only the first value is appended to the main array and im unsure of how to fix this in my code to what i require.
// The name of the file to open.
String fileName = "Details.txt";
String wfilename = "output.txt";
// This will reference one line at a time
String line = null;
String temp;
try {
// FileReader reads text files in the default encoding.
FileReader fileReader = new FileReader(fileName);
FileWriter fileWriter = new FileWriter(wfilename);
BufferedWriter bufferedWriter = new BufferedWriter(fileWriter);
// Always wrap FileReader in BufferedReader.
BufferedReader bufferedReader = new BufferedReader(fileReader);
List<String> parts = new ArrayList<>();
String [] temp2;
while((line = bufferedReader.readLine()) != null) {
//System.out.println(line);
temp = line;
temp2 = line.split(" ");
parts.add(temp2[0]);
//System.out.println(line);
bufferedWriter.write(line + "\n");
}
System.out.print(parts);
// Always close files.
bufferedReader.close();
bufferedWriter.close();
}
catch(FileNotFoundException ex) {
System.out.println("Unable to open file '" + fileName + "'");
}
catch(IOException ex) {
System.out.println("Error reading file '" + fileName + "'");
}
updated attempt:
I found that the reason for this was
parts.add(temp2[0]);
yet when I tried
parts.add(temp2)
i got hit with an error being
The method add(String) in the type List<String> is not applicable for the arguments (String[])
So basically what i am struggling with is adding an array into an array.
edit2:
I tried
for(int i=0; i<7; i++){
parts.add(temp2[i]);
}
which worked in that it added all the items in the file into one array. I was wondering if there was any method which can split the list every 7 terms to make it a 2D array?
This isnt required but i feel like for calculations it would be bad practice to use a for loop and do [i+7] when doing calculations for each line.