alvira
alvira

Reputation: 147

How to read all int data from a file

I want to read all int data from a file. But I only get the last line.

Content of the file:

1

2

3

Output:

3

Can can I get all numbers from a file?

    BufferedReader reader = new BufferedReader(new FileReader("C:\\Users\\...\\P.txt"));

    String zeile;
    try {

        while ((zeile = reader.readLine()) != null) {
            String in = reader.readLine();
            if (in != null) {
                int zahl = Integer.parseInt(reader.readLine());
                System.out.println(zahl);

            }
        }
    } catch (IOException e) {
        e.printStackTrace();

    } finally {
        reader.close();
    }

Upvotes: 1

Views: 73

Answers (2)

azro
azro

Reputation: 54168

You are calling readLine 3 times instead of one, but use its result only one, you already have the line in zeile variable. Also you can use the try-with-ressource to avoid the finally step

try (BufferedReader reader = new BufferedReader(new FileReader("C:\\Users\\...\\P.txt"))) {
    String zeile;
    while ((zeile = reader.readLine()) != null) {
        int zahl = Integer.parseInt(zeile);
        System.out.println(zahl);
    }
} catch (IOException e) {
    e.printStackTrace();
}

Upvotes: 2

StaticBeagle
StaticBeagle

Reputation: 5175

You are reading three values in one go.

while ((zeile = reader.readLine()) != null) { // first time. Read the 1
    String in = reader.readLine(); // second time. Read the 2
    if (in != null) {
        int zahl = Integer.parseInt(reader.readLine()); // third time. Read 3.
        System.out.println(zahl);

    }
}

You only need to read one at a time:

    while ((zeile = reader.readLine()) != null) {
            int zahl = Integer.parseInt(zeile);
            System.out.println(zahl);
    }

Upvotes: 2

Related Questions