Чтение строк текста из файла - PullRequest
1 голос
/ 04 февраля 2020

У меня есть текстовый файл, содержащий 5 клиентов (по 1 на строку), Клиент 1, Клиент 2, Клиент 3, Клиент 4 и Клиент 5. Используя следующий код, он отлично читает 5 строк текста;


import java.io.*;

public class CustomerIO  {

public void method () {

        try (BufferedReader br = new BufferedReader(new FileReader(new File ("Customers.txt")))) {
            int numberOfLines = readLines();
            String [] text = new String [numberOfLines];

            for (int i = 0; i < numberOfLines; i++) {
                text[i] = br.readLine();        
            }

            for (int i = 0; i < numberOfLines; i++) {
                System.out.println(text[i]);        
            }
        } catch (Exception e) {
            e.printStackTrace();
        }


    private int readLines() {

        try (BufferedReader br = new BufferedReader(new FileReader(new File ("Customers.txt")))) {

            while ((line = br.readLine()) != null) {
                numberOfLines++;
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
        return numberOfLines;
        }
          }

Однако, когда я переключаюсь на следующее, вывод: Customer 2, Customer 4, null


import java.io.*;

public class CustomerIO  {

    String line;
    int numberOfLines = 0;

    public void method () {

        try (BufferedReader br = new BufferedReader(new FileReader(new File ("Customers.txt")))) {

            while (br.readLine() != null) {
                System.out.println(br.readLine());
            }
        } catch (Exception e) {
            e.printStackTrace();
        }


    }

    private int readLines() {

        try (BufferedReader br = new BufferedReader(new FileReader(new File ("Customers.txt")))) {

            while ((line = br.readLine()) != null) {
                numberOfLines++;
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
        return numberOfLines;
        }
}

Основной метод содержится в следующем файле runner.class

public class Runner {

    public static void main(String[] args) {

        CustomerIO cus = new CustomerIO ();
        cus.method();
    }
}

Можете ли вы помочь мне понять, почему это происходит? Я хочу читать клиентов в arraylist, когда он правильно читает, а не работает со строкой [].

Спасибо

Ответы [ 2 ]

2 голосов
/ 04 февраля 2020

Проблема в том, что вы вызываете readline дважды для каждого l oop.

Вот ваш ошибочный код:

while (br.readLine() != null) {
    System.out.println(br.readLine());

Рабочее решение может быть:

String line = br.readline();
while (line != null) {
    System.out.println(line);
    line = br.readline()
}
0 голосов
/ 04 февраля 2020

Следующий код вызывает readLine() дважды за итерацию l oop, поэтому вы видите только все остальные строки:

while (br.readLine() != null) {
    System.out.println(br.readLine());
}

Вам необходимо назначить возвращаем значение в переменную, так что вы можете проверить на null.

Есть много способов сделать это, поэтому я покажу некоторые, в порядке убывания рекомендации.

// Using for loop (recommended)
//   Pro: Keeps the loop logic with the loop
//        Limits the scope of the variable
//        Smallest amount of code (lines of loop code: 2)
//   Con: Unusual construct
//        Inline assignment
for (String line; (line = br.readLine()) != null; ) {
    System.out.println(line);
}
// Using while loop with inline assignment
//   Pro: Common construct
//        Keeps the loop logic with the loop
//        Small amount of code (lines of loop code: 3)
//   Con: Variable scope not limited to the loop
//        Inline assignment
String line;
while ((line = br.readLine()) != null) {
    System.out.println(line);
}
// Using while loop without inline assignment
//   Pro: Common construct
//   Con: Loop logic both before and at end of loop
//        Variable scope not limited to the loop
//        More code (lines of loop code: 4)
//        Calling the readLine() method in two places
String line = br.readLine();
while (line != null) {
    System.out.println(line);
    line = br.readLine();
}
// Using break to exit forever loop
//   Pro: Limits the scope of the variable
//   Con: Loop logic both before and at end of loop
//        Using infinite loop and the break statement
//        More code (lines of loop code: 6)
for (;;) { // or: while (true)
    String line = br.readLine();
    if (line == null) {
        break;
    }
    System.out.println(line);
}
...