Как читать из файлов и хранить его в ArrayList объектов? - PullRequest
0 голосов
/ 24 февраля 2020

Это мой метод сохранения

public static void save() {
        try {
            PrintWriter myWriter = new PrintWriter("database.txt");
            for(int i=0; i<people.size(); i++) {
                myWriter.println(people.get(i).toString());
            }
            myWriter.close();
            System.out.println("Successfully wrote to the file.");
            menu();
        } catch (IOException e) {
            System.out.println("An error occurred.");
            e.printStackTrace();
        }
    }

Вот как это выглядит в файле

    Donald     Trump  23323.00

Это поля и имя массива

ArrayList<Person> people = new ArrayList<Person>();
public Person(String name, String password, double money) {
        this.name = name;
        this.password = password;
        this.money = money;
    }
constructors below.....

Как мне прочитать этот файл и сохранить его в массиве объектов? Нужна помощь: D

Ответы [ 2 ]

1 голос
/ 25 февраля 2020

Не то, чтобы что-то не так с тем, как вы записали свой текстовый файл с данными, просто я думаю, что лучше придерживаться более обычного формата файла CSV , который указан c для хранения данных этого типа.

Например, каждая строка в файле CSV считается строкой записи, и обычно запятая (,) используется для разделения столбцов данных поля в этой строке вместо пробела или табуляции (как в вашем файле) и для этого есть веская причина. В конце концов, эти данные в файле нужно будет извлечь, что если поле столбца содержит пробел в нем? Например, некоторые фамилии содержат два слова (Симона де Бовуар, Герберт М. Тернер III, Эшли М. Сент-Джон и др. c). Некоторое внимание должно быть уделено этому, и да, определенно есть обходной путь для этого, но в целом, просто использовать более конкретный c разделитель, чем этот пробел. Возможно, вы захотите изменить разделитель пробелов, возможно, через запятую или точку с запятой. Вы даже можете предоставить это как опцию в вашем Person class toString () методе:

/* Example Person Class...    */
import java.io.Serializable;

public class Person implements Serializable {

    // Default serialVersion id
    private static final long serialVersionUID = 1212L;

    private String name;
    private String password;
    private double money;

    public Person() { }

    public Person(String name, String password, double money) {
        this.name = name;
        this.password = password;
        this.money = money;
    }

    public String toString(String delimiterToUse) {
        return new StringBuffer("").append(this.name).append(delimiterToUse)
                                   .append(this.password).append(delimiterToUse)
                                   .append(String.format("%.2f", this.money)).toString();
    }

    @Override
    public String toString() {
        return new StringBuffer("").append(this.name).append(" ")
                                   .append(this.password).append(" ")
                                   .append(String.format("%.2f", this.money)).toString();
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public double getMoney() {
        return money;
    }

    public void setMoney(double money) {
        this.money = money;
    }
}

И в вашем save () способ, которым вы можете использовать существующую строку для использования разделителя пробелов по умолчанию (" "):

myWriter.println(people.get(i).toString());

или использовать другой разделитель, такой как комбинация запятая / пробел (", "):

    myWriter.println(people.get(i).toString(", "));

Записи данных в файле будут выглядеть примерно так:

Donald Trump, myPassword, 23323.0

Эту строку данных, расположенную выше, теперь будет проще анализировать, используя что-то вроде String # split () метод, например:

public static List<Person> readInPeople(String databaseFile) {
    /* Declare a List Interface to hold all the read in records 
       of people from the database.txt file.        */
    List<Person> people = new ArrayList<>();

    // 'Try With Resouces' is used to so as to auto-close the reader.
    try (BufferedReader reader = new BufferedReader(new FileReader("database.txt"))) {
        String dataLine;
        while ((dataLine = reader.readLine()) != null) {
            dataLine = dataLine.trim();
            // Skip past blank lines.
            if (dataLine.equals("")) {
                continue;
            }

            /* Split the read in dataline delimited field values into a 
               String Array. A Regular Expression is used within the split()
               method that takes care of any comma/space delimiter combination
               situation such as: "," or ", " or " ," or " , "   */
            String[] dataLineParts = dataLine.split("\\s{0,},\\s{0,}");

            // Ensure defaults for people.
            String name = "", password = "";
            double money = 0.0d;

            /* Place each split data line part into the appropriate variable 
               IF it exists otherwise the initialized default (above) is used. */
            if (dataLineParts.length >= 1) {
                name = dataLineParts[0];
                if (dataLineParts.length >= 2) {
                    password = dataLineParts[1];
                    if (dataLineParts.length >= 3) {
                        /* Make sure the data read in is indeed a string
                           representation of a signed or unsigned Integer 
                           or double/float type numerical value. The Regular
                           Expression within the String#matches() method 
                           does this.                                    */
                        if (dataLineParts[2].matches("-?\\d+(\\.\\d+)?")) {
                            money = Double.parseDouble(dataLineParts[2]);
                        }
                    }
                }
            }

            // Add the person from file into the people List.
            people.add(new Person(name, password, money));
        }
    }
    // Catch Exceptions...
    catch (FileNotFoundException ex) {
        System.err.println(ex.getMessage());
    }
    catch (IOException ex) {
        System.err.println(ex.getMessage());
    }
    /* Return the list of people read in from the 
       database text file.   */
    return people;
}

Чтобы использовать этот метод, вы можете сделать что-то вроде этого:

// Call the readInPeople() method to fill the people List.
List<Person> people = readInPeople("database.txt");

/* Display the people List in Console Window 
   using a for/each loop.     */
// Create a header for the data display.
// Also taking advantage of the String#format() and String#join() methods.
// String#join() is used to create the "=" Header underline.
String header = String.format("%-20s %-15s %s\n", "Name", "Password", "Money");
header += String.join("", Collections.nCopies(header.length(), "="));
System.out.println(header);

// Display the list. Also taking advantage of the printf() method.
for (Person peeps : people) {
    System.out.printf("%-20s %-15s %s\n", peeps.getName(), peeps.getPassword(), 
                      String.format("%.2f", peeps.getMoney()));
}

Экран консоли может выглядеть примерно так это:

Name                 Password        Money
===========================================
Donald Trump         myPassword      23323.00
Tracey Johnson       baseball        2233.00
Simone de Beauvoir   IloveFrance     32000.00
0 голосов
/ 24 февраля 2020

Прочитайте файл построчно и используйте тот же разделитель, который вы использовали в toString класса Person.

Как: пусть вы использовали " " в качестве разделителя.

затем прочитать строку за строкой и разделить данные с помощью этого разделителя и преобразовать данные соответственно

String line = reader.readLine();
String[] array = line.split(" ")// use same delimiter used to write
if(array.lenght() ==3){ // to check if data has all three parameter 
    people.add(new Person(array[0], array[1], Double.parseDouble(array[2]))); 
    // you have to handle case if Double.parseDouble(array[2]) throws exception
}
...