Go from .java to Binary

1

I have the following class:

public class Employees implements Serializable{

    private final ArrayList<Employee> llistaEmployees = new ArrayList<>();

    /**
     * Obte la llista d'llistaEmployees que conte la carpeta
     * @return ArrayList que conte les llistaEmployees de la carpeta
     */

    public List<Employee> getEmployees() {
        return llistaEmployees;
    }
}   


public class Employee implements Serializable{
    private String nom;
    private String empresa;
    private boolean jubilat;

    public String getNom() {
        return nom;
    }

    public void setNom(String nom) {
        this.nom = nom;
    }    

    public String getEmpresa() {
        return empresa;
    }

    public void setEmpresa(String empresa) {
        this.empresa = empresa;
    } 

    public boolean isJubilat() {
        return jubilat;
    }

    public void setJubilat(boolean jubilat) {
        this.jubilat = jubilat;
    }

    public Employee(){

    }

    public Employee (String nom,String empresa,boolean jubilat){
        this.nom=nom;
        this.empresa=empresa;
        this.jubilat=jubilat;
    }
}

And I have to do the following ... Read the file for example Datos.Txt which is where I have the information of the workers and save it in a binary file.

I mean I can read the information from an external file but I have no idea how to do it so that I can save it in another format using these classes ..

Can you help me?

For what I think I understand, it would be.

1- Read the file (I have it)

2- use it to create a list of employees 3- save that list in a binary file.

I'm pretty blocked .. I accept advice .. help .. examples ..: (

For example to read the external file I use this:

public class LecturaFitxer {
    /**
    * Mètode per llegir les dades d'un fitxer.
    * @param filePath d'on llegirem la informació dels employees
    * @throws FileNotFoundException excepcio
    * @throws IOException excepcio
    */ 

    @SuppressWarnings("ConvertToTryWithResources")
    public static void llegeixFitxer(String filePath) throws FileNotFoundException, IOException {
        try {
            File origen = new File(filePath);
            Scanner reader = new Scanner(origen);   
            String str; 

            while (reader.hasNextLine()){    
                str = reader.nextLine();    
                StringTokenizer st = new StringTokenizer(str);
                String[] strList = new String[st.countTokens()];

                for(int i=0; i<strList.length; i++){
                    strList[i] = st.nextToken();
                }

             System.out.println(strList[0]+"\t\t" +strList[1]+"\t" +strList[2]);
            }
            reader.close();
        } catch(FileNotFoundException ex){
            System.out.println("Error llegint el fitxer " + ex);
        } 
    }

    public static void main(String args[]) throws IOException{
        LecturaFitxer.llegeixFitxer(args[0]);
    }
}

Basically what I get is that arg [0] reads me the name, arg [1] the retirement date and the arg [2] the company.

Now what I do not know is that once I have read the file with its data, I use the employees class and I save everything in a bin file ...

    
asked by Montse Mkd 01.03.2017 в 20:14
source

3 answers

1

If you have a employees class, what you can do is create an "employee" for each loop of the WHILE loop and after the FOR loop.

Later, in an "ArrayList" created previously for example, you could go putting the employees right after creating them.

Finally you can put the ArrayList with the "employees" inside a file using the ObjectOutputStream class. Watch out! In order to save the objects created by you, you will need to implement the Serializable interface, even if they are inside an "ArrayList".

Employee Class The employee class will be declared as follows:

Class Employee implements Serializable {
  //Contenido de la clase
}

Private method is Jubilat () using Java 7:

In the same class where you do the operations you make a private auxiliary method that will determine if according to the date of birth of the "employee" if jubilat is true or false. This method is called where the parameter "jubilat" would go and you will have to pass the date of birth of the "employee" that is according to accounts strList 1 . The method is as follows:

public static boolean esJubilat(String fechaStr){

    String[] dma = fechaStr.split("/");
    int anio = Integer.parseInt(dma[2]);
    int mes = Integer.parseInt(dma[1]);
    int dia = Integer.parseInt(dma[0]);

    Calendar hoy = Calendar.getInstance(TimeZone.getDefault());

    //Pasamos el año, el mes y el dia
    Calendar fechaNac = new GregorianCalendar(anio, mes, dia);

    if (fechaNac.after(hoy)) {
        throw new IllegalArgumentException("No se puede hacer en el futuro");
    }

    int edad = hoy.get(Calendar.YEAR) - fechaNac.get(Calendar.YEAR);

    if(hoy.get(Calendar.DAY_OF_YEAR) < fechaNac.get(Calendar.DAY_OF_YEAR)) {
        edad-=1;
    }

    System.out.println("Años con Java7: "+edad);

    return edad >= 65;
}

Method is Jubilat using Java8:

This is the same as the previous one but shorter and easier but it only works if you use Java8

public static boolean esJubilat(String fechaStr) {
        //Version de Java8

        String[] dma = fechaStr.split("/");
        int anio = Integer.parseInt(dma[2]);
        int mes = Integer.parseInt(dma[1]);
        int dia = Integer.parseInt(dma[0]);

        LocalDate fechaNac = LocalDate.of(anio, mes, dia);
        LocalDate hoy = LocalDate.now();
        Period p = Period.between(fechaNac, hoy);

        System.out.println("Años con Java 8: "+p.getYears());
        return (p.getYears() >= 65);
    }

Afterwards, apart from t You have this other:

Procedure:

ArrayList<Employee> emps = new ArrayList<>(); //ArrayList para almacenar employees
try {
        File origen = new File(filePath);
        Scanner reader = new Scanner(origen);   
        String str; 

        while (reader.hasNextLine()){    
            str = reader.nextLine();    
            StringTokenizer st = new StringTokenizer(str);
            String[] strList = new String[st.countTokens()];

            for(int i=0; i<strList.length; i++){
                strList[i] = st.nextToken();
            }

            //Crear employee e insertarlo en el ArrayList creado previamente
            //Cuidado al crear el empleado. Los parametros que le pasas al c onstructor deben estar en el mismo orden en el que están declarados en el constructor.
            //strList[0] es el nombre de tipo String.
            //strList[2] es la empresa de tipo String.
            //strList[1] es la fecha de tipo String en formato "dia/mes/año"
            //el constructor dice que es public Employee(nom, empresa, jubilat). Jubilat es booleano por lo tanto:

            Employee emp = new Employee(strList[0], strList[2], NombreDeClaseDondeEstaDeclaradoElMetodo.esJubilat(strList[1]));
            //Recuerda que si has delcarado el metodo en la misma clase puedes llamarlo directamente con el nombre del metodo o con this.nombreMetodo().
            //Si vas a usar el método solo en esta clase ponlo como private.

            emps.add(emp); //Añadir employee al ArrayList

            System.out.println(strList[0]+"\t\t" +strList[1]+"\t" +strList[2]);
        }
        reader.close();

        try{

          //Crear Stream de objetos
          FileOutputStream fos = new FileOutputStream("emps.bin");
          ObjectOutputStream oos = new ObjectOutputStream(fos); //Recibe un FileOutputStream

          oos.writeObject(emps); //Escribir el ArrayList en el fichero

          oos.close();
          fos.close();
        } catch(IOException | ObjectStreamException exc) {
           System.out.println("Error en Stream de employees");
        }
    } catch(FileNotFoundException ex){
        System.out.println("Error llegint el fitxer " + ex);
    } 

Here A tutorial for ObjectOutputStream

Other Tutorial for Reading and Writing Objects.

With this method it is really easy to save and extract information in files, saving the Objects as they are serialized.

When you remove the ArrayList, then you will only have to go through it to get the information you want from the ArrayList. You can use it with HashMaps also for example, if you want to save each employee with a key in order to get a specific employee more quickly. I hope it was helpful.

    
answered by 01.03.2017 / 21:33
source
2

Let's see, the easiest thing is what our friend says "@Stefan Nolde", so that you will be much clearer, I will give you a complete example, therefore, the first thing; The JavaBean of Employe.java , you must implement Serializable , total, the code is left for you:

package fips;

import java.io.Serializable;

public class Employe implements Serializable{   
    private static final long serialVersionUID = 1L;

    private String nom;
    private String empresa;
    private boolean jubilat;

    // Constructores.
    public Employe() {
        super();
    }

    public Employe(String nom, String empresa, boolean jubilat) {
        this.nom = nom;
        this.empresa = empresa;
        this.jubilat = jubilat;
    }

    // Getters y Setters.
    public String getNom() {
        return nom;
    }

    public void setNom(String nom) {
        this.nom = nom;
    }

    public String getEmpresa() {
        return empresa;
    }

    public void setEmpresa(String empresa) {
        this.empresa = empresa;
    }

    public boolean isJubilat() {
        return jubilat;
    }

    public void setJubilat(boolean jubilat) {
        this.jubilat = jubilat;
    }

    // Re escritura de método heredado de Object.
    @Override
    public String toString() {
        return "Employe [nom = " + nom + " | empresa = " + empresa + " | jubilat = " + jubilat + "]";
    }   

}

Now, what you need is to write a binary file and then read it, which is the most normal thing, therefore, one way to do it, without getting too complicated is:

package fips;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.ArrayList;

public class Main {
    public static void main(String[] args) {
        // Crear Employes, en tu caso, desde el fichero txt.
        Employe a = new Employe("A", "HP", true);
        Employe b = new Employe("B", "ORACLE", false);
        Employe c = new Employe("C", "AMAZON", true);
        Employe d = new Employe("D", "SANTANDER", false);
        Employe e = new Employe("E", "FIPS", true);

        // Lo juntas en un objeto ya serializado, es decir, un ArrayList.
        ArrayList<Employe> employes = new ArrayList<>();
        employes.add(a);
        employes.add(b);
        employes.add(c);
        employes.add(d);
        employes.add(e);

        // Lo guardas en un fichero bonario, por ejemplo: employes.bin
        String ruta = "C:/TuUsuario/Escritorio/employes.bin";
        // Usamos try con recursos para olvidarnos de los cierres.
        try (ObjectOutputStream oos = new ObjectOutputStream(
                new FileOutputStream(ruta))){
            // Escribo el único objeto, que es el ArrayList.
            oos.writeObject(employes);
        }catch (IOException exception) {
            exception.printStackTrace();
        }

        // Leer fichero employes.bin
        try (ObjectInputStream ois = new ObjectInputStream(
                new FileInputStream(ruta))){
            // En nuestro caso, ya sabemos que lo que leeremos es un ArrayList.
            @SuppressWarnings("unchecked")
            ArrayList<Employe> objRead = (ArrayList<Employe>) ois.readObject();
            // Vemos sus datos.
            for (Employe employe : objRead) {
                System.out.println(employe.toString());
            }
        } catch (IOException exception) {
            exception.printStackTrace();
        } catch (ClassNotFoundException e1) {
            e1.printStackTrace();
        }

    }
}

And therefore, you already have the information accessible. Keep in mind that when using this form, it is best to just write one object per file, since when saving each object, a header is generated ... That will already be explained to you, but focus on having to save an object, and that object can contain the objects you want, and these must be serialized.

Anyway, so as not to wind me up, you'll have at the exit of the cosola:

Employe [nom = A | empresa = HP | jubilat = true]
Employe [nom = B | empresa = ORACLE | jubilat = false]
Employe [nom = C | empresa = AMAZON | jubilat = true]
Employe [nom = D | empresa = SANTANDER | jubilat = false]
Employe [nom = E | empresa = FIPS | jubilat = true]

I hope it serves you.

    
answered by 02.03.2017 в 12:01
1

The easiest way if you already implemented the Serializable interface of saving an object as a binary is to use a ObjectOutputStream :

Serializable employee = new Employee();
// colocar datos al employee
File archivo = new File("ruta/a/archivo")
ObjectOutputStream oos = new ObjectOutputStream(FileOutputStream(archivo));
oos.writeObject(employee);
oos.close();

That writes you a file with your complete object including its data. Just make sure that all the included fields are also Serializable .

It is recommended to catch a couple of possible exceptions with try...catch .

    
answered by 02.03.2017 в 06:06