Învață mecanismul de serializare în Java,,en,Urmăriți prin e-mail,,en,Google ,,en,techalpine.com/video-tutorials/spring-framework/spring-boot,,en,& Gt;,,en,Ne vizitați,,en,Urma,,en?

Serialize and de-serialize in Java

Serializați și de-serializați în Java,,en,Una dintre forțele fundamentale ale Java este mecanismul de serializare,,en,Aceasta este în esență serializarea obiectelor Java,,en,unde obiectul este persistent ca o secvență de octeți,,en,Depozitarea persistentă poate fi sistemul de fișiere,,en,baza de date sau fluxurile,,en,deserializarea este doar procesul invers,,en,unde secvențele octeților sunt din nou convertite înapoi în obiecte,,en,Punctul important de reținut este că obiectul este stocat în starea sa actuală și inversat înapoi numai la acea stare,,en,vom încerca să explorăm conceptele de bază ale serializării obiectului Java și să lucrăm și la unele exemple de codificare,,en,De ce avem nevoie de serializare,,en,Totul în Java este reprezentat ca obiecte,,en,într-o aplicație Java,,en,fie ea autonomă,,en,întreprindere sau în altă formă,,en,trebuie să te ocupi de obiecte,,en

Prezentare generală:

One of the fundamental strength of Java is its serialization mechanism. This is basically serialization of Java objects, where the object is persisted as a sequence of bytes. The persistent storage can be file system, database or streams. And, deserialization is just the reverse process, where the sequences of bytes are again converted back into objects. The important point to note is that the object is stored in its current state and reversed back to that state only.

In this article, we will try to explore the core concepts of Java object serialization and also work on some coding examples.


 

Why we need serialization?

Everything in Java is represented as objects. So, in a Java application, be it stand-alone, enterprise or in some other form, you need to deal with objects. Aceste obiecte au propriile lor stări,,en,stările nu sunt altceva decât valoarea sau datele pe care le conține în orice moment al timpului,,en,și variază din când în când,,en,Într-o aplicație,,en,dacă trebuie să stocăm date,,en,îl putem stoca într-o bază de date sau într-un sistem de fișiere,,en,sub formă de fișiere,,en,apoi recuperați-o ori de câte ori este necesar,,en,aceasta este de obicei manipularea și stocarea datelor brute,,en,dacă trebuie să stocăm un obiect,,en,cu starea și valoarea sa actuală,,en,nu putem folosi baza de date sau sistemul de fișiere direct,,en,Pentru că ei nu înțeleg obiectul,,en,asa de,,en,trebuie să-l stocăm sub formă de octeți,,en,Acest mecanism este valabil și atunci când trebuie să transferăm un obiect în rețea,,en,întrebarea este - ',,en,Cum realizăm această sarcină ",,en,este soluția la această problemă,,en,Acesta poate fi, de asemenea, definit ca un protocol,,en (states are nothing but the value or data it contains at any point of time) and it varies from time to time.

In an application, if we need to store data, we can store it in a database or file system (in the form of files). And, then retrieve it whenever required. Dar, this is typically handling and storing the raw data.

Now, if we need to store an object (with its current state and value) we cannot use database or file system directly. Because they do not understand object, so, we need to store it in the form of bytes. This mechanism is also applicable when we need to transfer an object over network.







Dar, the question is – ‘How do we perform this task’? Serialization is the solution to this problem. It can also be defined as a protocol, care poate fi folosit de orice parte pentru a serializa sau a de-serializa un obiect,,en,Următoarele sunt cele mai importante două scopuri pentru care serializarea este utilizată pe scară largă,,en,Persistă obiectele stocate,,en,Sistemul de fișiere,,en,curent,,en,Transferați obiecte pe rețea,,en,Unele concepte înrudite,,en,Înainte de a trece în secțiunile următoare pe mecanisme de serializare și eșantioane de cod,,en,trebuie să înțelegem câteva concepte tehnice de bază utilizate în procesul de serializare,,en,serialVersionUID,,en,Aceasta este în esență identificarea unui obiect serializat,,en,Se folosește pentru a se asigura că obiectele serializate și de-serializate sunt identice,,en,Uneori acest UID este, de asemenea, utilizat în scopul refactorizării,,en,Mai multe detalii pot fi găsite,,en,Interfața de marcare,,en,Pentru a implementa serializarea în Java sau pentru a face un obiect serializabil,,en,trebuie să implementați,,en,Serializabil este o interfață marker,,en.

Following are the two most important purpose for which serialization is widely used.

  • Persists objects in storage (Database, file system, stream)
  • Transfer Objects over network

Some related concepts

Before moving into the next sections on serialization mechanisms and code samples, we must understand some basic technical concepts used in the serialization process.

serialVersionUID: This is basically the identification of a serialized object. It is used to ensure that the serialized and de-serialized objects are same. Sometime this UID is also used for refactoring purpose. More details can be found here.

Marker Interface: To implement serialization in Java or making an object serializable, you need to implement Serializable interface. Serializable is a marker interface, ceea ce înseamnă că este o interfață fără câmpuri și metode,,en,pentru implementarea unor comportamente speciale,,en,Există și alte interfețe de markere disponibile în Java,,en,Cuvânt cheie tranzitorie,,en,Acesta este un cuvânt cheie foarte important în Java,,en,Este posibil să fie necesară stocarea unei părți a unui obiect și evitarea unor câmpuri care pot conține informații sensibile, cum ar fi numărul cardului de credit,,en,parola etc,,en,trebuie doar să definim acele câmpuri ca,,en,'tranzitoriu,,en,și nu va permite ca aceste câmpuri să fie salvate în timpul procesului de serializare,,en,Cursuri de flux de obiecte,,en,Două clase de flux de obiecte sunt foarte importante pentru serializarea și procesul de serializare,,en,Acestea sunt ObjectOutputStream și ObjectInputStream,,en,Vom verifica implementarea în următoarea secțiune de cod,,en,Cum funcționează serializarea - Exemple de coduri,,en, for implementing some special behaviour. There are also other marker interfaces available in Java.

Transient Keyword: This is a very important keyword in Java. There may be a need to store a part of an object and avoid some fields which may contain sensitive information like credit card number, password etc. Here, we just need to define those fields as ‘transient’, and it will not allow those fields to be saved during the serialization process.

Object Stream classes: Two object stream classes are very important for serialization and de-serialization process. Those are ObjectOutputStream and ObjectInputStream. We will check the implementation in the following code sample section.

How serialization works – Some code Examples

În acest exemplu de codificare vom avea trei clase Java așa cum am menționat mai jos,,en,clasa java reprezentând obiectul care urmează să fie serializat,,en,java pentru serializarea obiectului Student,,en,java pentru a extrage valorile din obiectul Student salvat,,en,Urmează cursul Student cu câteva domenii relevante,,en,Vă rugăm să rețineți că ",,en,PWD“,,en,câmpul este marcat ca ",,en,tranzitoriu',,en,pentru a evita salvarea acesteia ca parte a obiectului,,en,Celelalte câmpuri vor fi salvate ca parte a obiectului Student,,en,Codul eșantionului clasei de studenți,,en,clasa publică Student implementează java.io.Serializable,,en,numele public String,,en,adresă publică String,,en,public String userId,,en,punga publică tranzitorie pwd,,en,public void objectCheck,,en,adresa ,,en,numele de utilizator,,en,clasa este concepută pentru a serializa obiectul Student așa cum se arată mai jos,,en,Creează un obiect Student și îl salvează într-un fișier numit ",,en.

  • java class representing the object to be serialized
  • java class for serializing Student object
  • java class to extract the values from the saved Student object

Following is the Student class with some relevant fields. Please note that the ‘pwd’ field is marked as ‘transient’ to avoid saving it as a part of the object. The other fields will be saved as part of the Student object.







Listing1: Student class sample code

[cod]

public class Student implements java.io.Serializable

{

public String name;

public String address;

public String userId;

public transient String pwd;

public void objectCheck()

{

Println(“Student details ” + nume + ” ” + address ” “+ userId);

}

}

[/cod]

Now, the 2nd class is designed to serialize Student object as shown below. It creates a Student object and save it in a file named ‘student.ser“,,en,în sistemul de fișiere locale,,en,Serializarea obiectului clasei Student,,en,clasa publică SerializeExemplu,,en,Student st = student nou,,en,st.name =,,en,Allen,,en,adresa =,,en,TX,,en,st.userId =,,en,ALN,,en,st.pwd =,,en,Aln123 $,,ar,Creați fluxul de ieșire fișier,,en,FileOutputStream fileOutStr =,,en,student.ser,,en,Creați fluxul de ieșire obiect și scrieți obiectul,,en,ObjectOutputStream objOutStr = ObjectOutputStream nou,,en,fileOutStr,,en,objOutStr.writeObject,,en,Închideți toate fluxurile,,en,objOutStr.close,,en,fileOutStr.close,,en,System.out.printf,,en,Datele serializate sunt salvate într-un fișier,,en,Rezultatul din această clasă este prezentat mai jos,,en,Se afișează rezultatul serializării,,en,clasa este proiectat pentru a de-serializa obiectul Student salvat și extrage valorile din acesta,,en,Valorile extrase vor fi afișate în consola Java,,en,De-serializarea obiectului Student,,en,clasa publica DeserializeExemplu,,en,Creați un obiect student,,en,Student st = null,,en,FileInputStream fileInStr = nou FileInputStream,,en in the local files system.

Listing2: Serializing Student class object

[cod]

import java.io.*;

public class SerializeExample

{

public static void main(Șir [] args)

{

Student st = new Student();

st.name = “Allen”;

st.address = “TX, Statele Unite ale Americii”;

st.userId = “Aln”;

st.pwd = “Aln123$”;

încerca

{

//Create file output stream

FileOutputStream fileOutStr =

new FileOutputStream(“student.ser”);

//Create object output stream and write object

ObjectOutputStream objOutStr = new ObjectOutputStream(fileOutStr);

objOutStr.writeObject(st);

//Close all streams

objOutStr.close();

fileOutStr.close();

System.out.printf(“Serialized data is saved in a file – student.ser”);

}prinde(IOException exp)

{

exp.printStackTrace();

}

}

}

[/cod]

Output from this class is shown below.

Serialization

Image 1: Showing serialization output

The 3rd class is designed to de-serialize the saved Student object and extract the values from it. The extracted values will be shown on the Java console.


 

Listing3: De-serializing Student object

[cod]

import java.io.*;

public class DeserializeExample

{

public static void main(Șir [] args)

{

//Create student object

Student st = null;

încerca

{

FileInputStream fileInStr = new FileInputStream(“student.ser”);

ObjectInputStream objInStr = ObjectInputStream nou,,en,fileInStr,,en,st =,,en,objInStr.readObject,,en,objInStr.close,,en,fileInStr.close,,en,ClassNotFoundException cexp,,en,Clasa de studenți nu a fost găsită,,en,cexp.printStackTrace,,en,Student deserializat,,en,st.name,,en,st.address,,en,Numele de utilizator,,en,st.userId,,en,st.pwd,,en,Rețineți că ieșirea nu imprimă valoarea parolei,,en,deoarece a fost declarată tranzitorie,,en,Se afișează ieșirea de serializare,,en,Unele implementări ale vieții reale,,en,să aruncăm o privire asupra unor implementări ale serialei din viața reală,,en,Vă va ajuta să înțelegeți importanța și utilizarea persistenței obiectului,,en,Gândiți-vă la o aplicație de joc în care statul este foarte important,,en,când un utilizator a părăsit jocul în orice moment,,en,starea este serializată și stocată într-un anumit tip de spațiu de stocare,,en,În timp ce utilizatorul dorește să reia jocul din nou,,en(fileInStr);

st = (Student) objInStr.readObject();

objInStr.close();

fileInStr.close();

}prinde(IOException exp)

{

exp.printStackTrace();

return;

}prinde(ClassNotFoundException cexp)

{

Println(“Student class not found”);

cexp.printStackTrace();

return;

}

Println(“Deserialized Student…”);

Println(“Nume: ” + st.name);

Println(“Address: ” + st.address);

Println(“User Id: ” + st.userId);

Println(“Password: ” + st.pwd);

}

}

[/cod]

Output from this class is shown below. Please note that the output does not print the value of the password, as it was declared as transient.

De-serialization

Image 2: Showing de-serialization output

Some real life implementations

In this section, let us have a look at some of the real life implementations of serialization. It will help you understand the importance and the usage of object persistence.

  • Think of a game application where the state is very important. Now, when a user left the game at any point of time, the state is serialized and stored in some type of storage. While the user wants to re-start the game again, aceeași stare a obiectului este recreată de procesul de serializare,en. So, nothing is lost in the whole process.
  • The other important example is ATM application. When a user request some withdrawal from an ATM machine (which is the client), the request is sent to the server as a serialized object. On the server end, the reverse process (de-serialization) is executed and the action is performed. This is an example of how serialization works over network communication.
  • Stock market update is another example where the update is stored as a serialized object and served to the client whenever required.
  • In any web application, the user session information is very important to maintain. Because, if at any point of time, the application fails or internet does not work, utilizatorul este deconectat de la aplicație în mijlocul unei anumite activități,en. Now, this half-done activity is stored as a serialized object, and restored when connection is established again. As a result, the user can continue from the same point where he left his activity.

Concluzie:

Java serialization is a very important feature to learn. In this article, we have discussed serialization in details along with its relevant concepts. We have also explained one coding example to show how serialization works. The example can be enhanced or modified to perform addition tasks. Overall, serialization is very flexible in nature, but the developers need to know the tricks and tips to implement it properly. Hope this article will provide you a guidance to move forward.








 

============================================= ============================================== Buy best TechAlpine Books on Amazon
============================================== ---------------------------------------------------------------- electrician ct chestnutelectric
error

Enjoy this blog? Please spread the word :)

Follow by Email
LinkedIn
LinkedIn
Share