Nicolas
Nicolas

Reputation: 11

Java Reading Text Inside File

![enter image description here][1]I have a file called notes.txt containing several lines of text that I want show to my JPanel.

Here is my code:

private void loadNotes() {
    File file = new File("notes.txt");
    if (file.exists()) {
        try {
            FileInputStream fs = new FileInputStream(file);
            BufferedReader br = new BufferedReader(
                    new InputStreamReader(fs));

            for (int i = 0; i < notes.length; i++) {
                if (br.readLine() != null) {
                    String note = br.readLine();
                    System.out.println(note);
                    notes[i] = new JCheckBox(note, false);
                    panel.add(notes[i]);
                    panel.revalidate();
                    panel.repaint();
                }
            }
            br.close();

        } catch (Exception e1) {
        }
    } else {
        System.out.println("File does not exist");
    }
}
            br.close();

This method grabs the lines from the file and prints out the check boxes. So if I have 4 notes then it prints out 4 checkboxes. However, it doesn't print out the text? Why not?

https://i.sstatic.net/SDtMm.png

Upvotes: 0

Views: 65

Answers (1)

Reimeus
Reimeus

Reputation: 159864

You're calling br.readLine() twice in the for loop so every second line of the file will be skipped. Assign the note variable at the start of the loop

String note;
for (int i = 0; i < notes.length; i++) {
    if ((note = br.readLine()) != null) {
        ...
    }
}

Upvotes: 4

Related Questions