I need help reading the contents of a text file and saving each line as String in an array. For example, the text file contains the data:
°C
12,0
21,9
And I want to read each line into an array like:
line[0] = first_ine; //°C
line[1] = secondLine; //12,0
line[2] = thirdLine; //21,9
My aim is to be able to access any of the lines I've stored in the array and print its content on a label like:
labelWithText.setText(line[0]);
Ok. Here is a version of my code in which I'm trying to use arrays to store each line of the text file in an array field. It results in an ArrayOutOfBound error.
try {
input = new FileInputStream(new File("DataFiles/myData.txt"));
CharsetDecoder decoder = Charset.forName("ISO-8859-1").newDecoder();
decoder.onMalformedInput(CodingErrorAction.IGNORE);
InputStreamReader reader = new InputStreamReader(input, decoder);
BufferedReader buffReader = new BufferedReader(reader);
StringBuilder stringBuilder = new StringBuilder();
String line = buffReader.readLine();
int i = 0;
String lineContent[] = line.split("\n");
while(line != null) {
stringBuilder.append(line).append(System.getProperty("line.separator"));
line = buffReader.readLine();
lineContent[i] = line;
i++;
}
buffReader.close();
nomDataLabel.setText(lineContent[0]);
minDataLabel.setText(lineContent[1]);
maxDataLabel.setText(lineContent[2]);
} catch (Exception e) {
e.printStackTrace();
}