Reputation: 27
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();
}
Upvotes: 0
Views: 991
Reputation: 3235
Average Joe here are two methods to load the dictionary.txt file
One puts the data in a String[] Arrray the other in a ArrayList dictionary
A side note the Buffered Reader is about 6 to 9 times faster than the Scanner method
For an array list :
ArrayList<String> dictionary = new ArrayList<>();
private void onLoad() throws FileNotFoundException, IOException {
long start2 = System.nanoTime();
try (BufferedReader input = new BufferedReader(new FileReader("C:/A_WORDS/dictionary.txt"))) {
for (String line = input.readLine(); line != null; line = input.readLine())
dictionary.add(line);
input.close();
}
For a simple array :
String[] simpleArray;
private void loadFile() throws FileNotFoundException, IOException {
File txt = new File("C:/A_WORDS/dictionary.txt");
try (Scanner scan = new Scanner(txt)) {
data = new ArrayList<>() ;
while (scan.hasNextLine())
data.add(scan.nextLine());
simpleArray = data.toArray(new String[]{});
int L = simpleArray.length;
System.out.println("@@@ L "+L);
}
}
Upvotes: 3