Reading and Writing an Object Array List to a file

How to implement writing an object Array List to a file: txt or xml. Please explain this with specific examples. I'm doing a course on OOP in Java. The following code is available:

package main;
import java.io.Serializable;
import java.util.Scanner;

public class User implements Serializable {
 private final String ANSI_BLUE = "\u001B[34m";
 Scanner in = new Scanner(System.in);
 private String Name;
 private String tel;

public String SetName(){
    System.out.print("Введите имя пользователя: "); //ADD NAME OF USER
    Name = in.nextLine();
    return Name;
}
public String SetTel(){
    System.out.print("Введите телефон пользователя: "); //ADD TEL OF USER
    tel = in.nextLine();
    return tel;
}
public String GetName(){
    return Name;
}
public String GetTel(){
   return tel; 
}
public void show_all(){
   System.out.println(ANSI_BLUE + "Пользователь:"); //USER
   System.out.println("Имя: " + GetName()); //NAME
   System.out.println("Телефон: " + GetTel()); //TELL
}
}

The User class is responsible for creating the User object itself.

    public class Users implements Serializable{
    public static final String ANSI_RED = "\u001B[31m";
    public static final String ANSI_RESET = "\u001B[0m";
    public static final String ANSI_GREEN = "\u001B[32m";
    public static final String ANSI_PURPLE = "\u001B[35m";
    ArrayList<User> users;
    private int count = 0; 

    public Users(ArrayList<User> users, int count){
        this.users = users;
        this.count = count;
    }    


    public void Add(){
        System.out.println();
        System.out.println(ANSI_GREEN + "Добавьте пользователя!" + ANSI_RESET );  //Add a User
        while(count  >= 0){
            User user = new User();
            user.SetName();
            user.SetTel();
           // System.out.println("Значение index: " + count);
            users.add(count, user);
            count++;
            System.out.println();
            break;
        }
    }   
    public void Show_All(){
        System.out.println();
        for (int i = 0; i < users.size(); i++) {
        users.get(i).show_all();
         System.out.println("ID: " + i);
         System.out.println();
         //System.out.println("Значение count: " + count);
        }
    }
    public void Remove_User(int i){
        users.get(i).show_all();
        System.out.println("ID: " + i);
        users.remove(i);
        count = count - 1;
        System.out.println(ANSI_PURPLE + "Удалён" + ANSI_RESET); //User Deleted
        System.out.println();
    }
    public void Save_Users() throws IOException{
        Users users = new Users();
        Serialization save = new Serialization();
        save.Save(users);
    } 
    public void main(String[] args) throws IOException {       
        Users users = new Users();
         int e = 1;       
        while (e != 0)
    {
        System.out.println(ANSI_RED + "Выберите комманду" + "\u001B[0m");
        System.out.println("1 - Добавить пользователя\n2 - Вывести всех пользователей\n3 - Удалить пользователя\n4 - Сохранить и выйти\n");
        System.out.print("Введенная команда: ");
        Scanner in = new Scanner(System.in);
        char y;
        y = in.next().charAt(0);
           switch(y)
            {
                case '1' :
                users.Add(); //users.Add();
                break;

                case '2' :
                users.Show_All();
                break;

                case '3' :
                System.out.println();
                System.out.print(ANSI_GREEN + "Введите ID пользователя: "  + ANSI_RESET);
                int i = in.nextInt();
                users.Remove_User(i);
                break;

                case '4' :
                System.out.print(ANSI_RED + "Сохранение данных " + ANSI_RESET);
                users.Save_Users();
                System.exit(0);
                break;
            }
        }    
    }  
}

In the Users class, an object ArrayList is created for the User. For further dynamic use. Output via a byte stream.

public class Serialization {
    public void Save(Users users) throws IOException{
        File file = new File("users.dat");
        ObjectOutputStream oos = null;
        FileOutputStream fos = new FileOutputStream(file);
        oos = new ObjectOutputStream(fos);
        oos.writeObject(users);
        oos.close();
    }
}

The problem is that after adding the constructor.

public Users(ArrayList<User> users, int count){
        this.users = users;
        this.count = count;
    }  

To create an instance of Users users = new Users(); (which we then write to the file in the saveUser () method, it is also used in the menu to call the add, delete, and output functions of all users), the following error occurs:

Constructor Users in class Users cannot be applied to given types; required: ArrayList,int found: no arguments reason: actual and formal argument lists differ in length

I don't understand which ones use formal parameters.. for this instance. And whether the program will then correctly serialize my list with User objects, and not the empty list itself.

Author: Flavie Brilliants, 2018-11-04

1 answers

In order to write the Users class with all its instance variables, you need to use object serialization. Serialization is like a written (compressed) object.Imagine an inflatable figure. You can lower the inflatable figure and put it in a box, for example.And if you did not, then the inflated figure is unlikely to fit in a small box.

Lower the shape and put it in the box-Serialization

Pull out the shape and inflate it - Diserialization

As it were, you can save the object data(state, instance variables) in txt and make a constructor to pass line-by-line parameters for the NEW object.But you need something else. It is "blow away" the object and put it in the file.You can do this as follows:

The class of the object to be descended (serialized) must implement the Serializable interface

public class Users implements Serializable {

}

Now pay attention!

In order to serialize an object with all its fields(instance variables) NEED so that all its object references also implement the Serializable

public class User implements Serializable{
}

Most classes already implement the Serializable interface for you,and some can't at all.

Go ahead:

In order to write the Users object to a file,we need to use streams the connection stream is a simple byte stream(FileInputStream (incoming), FileOutputStream (outgoing).

And streams, in which we will cram objects in,and there they will shrink or inflate : ObjectInputStream(incoming-inflate) ObjectOutputStream(Outgoing-deflate).

Example :

public void main(String[] args){
    try{
       //Записываем в файл объект Users(спускаем фигуру и запихиваем в коробку)
      Users users = new Users();
      FileOutputStream fos = new FileOutputStream("имя файла");    
      ObjectOutputStream oos = new ObjectOutputStream(fos);
      oos.close();//oos - это внешний поток.Если мы закрываем внешний то и 
      внутренний тоже.

      //Читаем с файла объект Users(достаем фигуру с коробки и надуваем)
      FileInputStream fis = new FileInputStrea("имя коробки");
      ObjectInputStream ois = new ObjectInputStream(fis);
      Object obj= ois.readObject();//Получаем объекты в том порядке,в котором 
      //записывали(Спустили фигуру собачки и положили в коробку первую,значит
      //и достаем тогда её первой и надуваем
      //Так как Object нужно привести к типу ниже в иерархии
      Users users = obj;
      ois.close();

    catch(IOException ex){
    ex.printStackTrace();
}catch(ClassNotFoundException ex){
 //Данное исключение может появиться,если класс объекта,
 //которые мы хотим надуть не найден.
    ex.printStackTrace();
}

In this example, I wrote a Users object to a file that contains an ArrayList For if you write only the ArrayList users object to a file, what good is it if your Users class doesn't have a constructor or some method to accept the ArrayList users object.

And all the methods you need they are in the Users class. To make sense to write an ArrayList you need to do the following:

 public class Users {
    ArrayList<Users> users;

    public Users(ArrayList<Users> users){
        this.users = users;
    }
  }

I think you've got the gist!Thanks for your attention!

 0
Author: skoriy, 2018-11-05 00:24:54