0

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();
}
0009laH
  • 1,960
  • 13
  • 27
AverageJoe
  • 27
  • 7
  • Look into `List fileContent = Files.readAllLines(Paths.get("FilePathHere"), StandardCharsets.UTF_8)` – Matt Nov 18 '19 at 15:35
  • Does this answer your question? [How to read a large text file line by line using Java?](https://stackoverflow.com/questions/5868369/how-to-read-a-large-text-file-line-by-line-using-java) – SedJ601 Nov 18 '19 at 15:38
  • 2
    I would suggest you spend more time learning Java basics. If you can't do the basics, it will make JavaFX a little harder to learn. – SedJ601 Nov 18 '19 at 15:39
  • "I keep getting NullPointer errors and ArrayIndexOutOfBoundException" where, exactly? – Federico klez Culloca Nov 18 '19 at 15:44
  • Thank you guys for your quick response! @FedericoklezCulloca I get the OutOfBound error whenever I define an array within the while loop an try to use to use it. All the data is stored in field index 0. So `fieldIndex[1]` results in an OutOf Bound error. – AverageJoe Nov 18 '19 at 16:10
  • 2
    I think you need to update the code you have posted because there is no array – Matt Nov 18 '19 at 16:48
  • 2
    I recommend prividing the detailed info about a single version of your code. Mentioning a bunch of errors that you got while experimenting around just distracts us. Btw: Unless you want to write the data to a file (or a similar output), using the same line seperator that your system uses is not necessary. JavaFX's controls are very well capable of understanding `"\n"` even if e.g. windows uses a different sequence of chars... – fabian Nov 18 '19 at 17:39
  • I've updated my code segment. Sorry for the trouble. In this version I'm trying to use arrays to store each line of the text file in a different array index. code compilation seems fine. The ArrayOutOfBound error fires only when I try to run the code. – AverageJoe Nov 19 '19 at 08:44

1 Answers1

3

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);
    }
}
0009laH
  • 1,960
  • 13
  • 27
Vector
  • 3,066
  • 5
  • 27
  • 54
  • Thank you so much, Grendel! Your code works for me. I'm currently using the BufferedRead method for performance reasons. Thank you for the informative side note!!! – AverageJoe Nov 21 '19 at 09:56
  • @AverageJoe I seldom ask this but could you accept the answer as solving your question – Vector Nov 22 '19 at 01:26
  • I've already accepted your answer :-). However it says **"Thanks for the feedback! Votes cast by those with less than 15 reputation are recorded, but do not change the publicly displayed post score."** – AverageJoe Nov 22 '19 at 10:11