2.14 学习总结 之 序列化

一、说在前面

昨天 使用layui重构选课系统
今天 学习序列化的相关知识

 

 

 

 

二、序列化介绍

1、序列化概念:

  序列化 (Serialization)是将对象的状态信息转换为可以存储或传输的形式的过程。在序列化期间,对象将其当前状态写入到临时或持久性存储区。以后,可以通过从存储区中读取或反序列化对象的状态,重新创建该对象。

1)序列化可以将序列化的对象通过子节流后存储到文件,数据库,云端。

2)使用时取出字节码,反序列化字节转换为对象,使用。

 

 

 

 

2、序列化的应用:

1)数据持久化:比如一个电商平台,有数万个用户并发访问的时候会产生数万个session 对象,这个时候内存的压力是很大的。我们可以把session对象序列化到硬盘中,需要时在反序列化,减少内存压力。

2)网络传输:我们将系统拆分成多个服务之后,服务之间传输对象,不管是何种类型的数据,都必须要转成二进制流来传输,接受方收到后再转为数据对象。

......

3、Android实现序列化的三种方式

 

 

三、序列化案例演示

1、UI界面

2、保存(序列化)

 

 3、读取(反序列化并使用)

 

四、代码

1、界面

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <androidx.constraintlayout.widget.Guideline
        android:id="@+id/guideline"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:orientation="vertical"
        app:layout_constraintGuide_percent="0.1" />

    <androidx.constraintlayout.widget.Guideline
        android:id="@+id/guideline2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:orientation="horizontal"
        app:layout_constraintGuide_percent="0.55" />

    <EditText
        android:id="@+id/editTextName"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:ems="10"
        android:hint="@string/input_name"
        android:importantForAutofill="no"
        android:inputType="textPersonName"
        app:layout_constraintBottom_toTopOf="@+id/editTextAge"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.1"
        app:layout_constraintStart_toStartOf="@+id/guideline"
        app:layout_constraintTop_toTopOf="parent" />

    <EditText
        android:id="@+id/editTextAge"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:ems="10"
        android:hint="@string/input_age"
        android:importantForAutofill="no"
        android:inputType="number"
        app:layout_constraintBottom_toTopOf="@+id/editTextChinese"
        app:layout_constraintEnd_toEndOf="@+id/editTextName"
        app:layout_constraintStart_toStartOf="@+id/editTextName"
        app:layout_constraintTop_toBottomOf="@+id/editTextName" />

    <EditText
        android:id="@+id/editTextChinese"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:ems="10"
        android:hint="@string/input_chinese"
        android:importantForAutofill="no"
        android:inputType="number"
        app:layout_constraintBottom_toTopOf="@+id/editTextEnglish"
        app:layout_constraintEnd_toEndOf="@+id/editTextAge"
        app:layout_constraintStart_toStartOf="@+id/editTextAge"
        app:layout_constraintTop_toBottomOf="@+id/editTextAge" />

    <EditText
        android:id="@+id/editTextEnglish"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:ems="10"
        android:hint="@string/input_english"
        android:importantForAutofill="no"
        android:inputType="number"
        app:layout_constraintBottom_toTopOf="@+id/editTextmath"
        app:layout_constraintEnd_toEndOf="@+id/editTextChinese"
        app:layout_constraintStart_toStartOf="@+id/editTextChinese"
        app:layout_constraintTop_toBottomOf="@+id/editTextChinese" />

    <EditText
        android:id="@+id/editTextmath"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:ems="10"
        android:hint="@string/input_math"
        android:importantForAutofill="no"
        android:inputType="number"
        app:layout_constraintBottom_toTopOf="@+id/guideline2"
        app:layout_constraintEnd_toEndOf="@+id/editTextEnglish"
        app:layout_constraintStart_toStartOf="@+id/editTextEnglish"
        app:layout_constraintTop_toBottomOf="@+id/editTextEnglish" />

    <TextView
        android:id="@+id/textViewGrade"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textSize="@dimen/deng_ji"
        app:layout_constraintBottom_toTopOf="@+id/guideline2"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.8"
        app:layout_constraintStart_toStartOf="@+id/guideline"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintVertical_bias="0.35"
        tools:text="-" />

    <Button
        android:id="@+id/buttonSave"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/btu_save"
        android:textSize="18sp"
        app:layout_constraintBottom_toTopOf="@+id/buttonRead"
        app:layout_constraintEnd_toEndOf="@+id/buttonRead"
        app:layout_constraintHorizontal_bias="0.0"
        app:layout_constraintStart_toStartOf="@+id/buttonRead"
        app:layout_constraintTop_toTopOf="@+id/guideline4" />

    <Button
        android:id="@+id/buttonRead"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/btu_read"
        android:textSize="18sp"
        app:layout_constraintBottom_toTopOf="@+id/guideline2"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.882"
        app:layout_constraintStart_toStartOf="@+id/guideline"
        app:layout_constraintTop_toBottomOf="@+id/buttonSave" />

    <androidx.constraintlayout.widget.Guideline
        android:id="@+id/guideline4"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:orientation="horizontal"
        app:layout_constraintGuide_percent="0.35" />
</androidx.constraintlayout.widget.ConstraintLayout>

2、数据类(学生对象)

package com.me.xvleihua1;

import java.io.Serializable;

public class Student implements Serializable {
    private String name;
    private int age;
    private Score score;

    public Student(String name, int age, Score score) {
        this.name = name;
        this.age = age;
        this.score = score;
    }

    public String getName() {
        return name;
    }

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

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    public Score getScore() {
        return score;
    }

    public void setScore(Score score) {
        this.score = score;
    }
}
class Score implements Serializable{
    private int math;
    private int english;
    private int chinese;
    private String grade;

    public Score(int math, int english, int chinese) {
        this.math = math;
        this.english = english;
        this.chinese = chinese;
        if(math>90&&chinese>90&&english>90){
            this.grade = "A";
        }else if(math>80&&chinese>80&&english>80){
            this.grade = "B";
        }else{
            this.grade = "C";
        }
    }

    public int getMath() {
        return math;
    }

    public void setMath(int math) {
        this.math = math;
    }

    public int getEnglish() {
        return english;
    }

    public void setEnglish(int english) {
        this.english = english;
    }

    public int getChinese() {
        return chinese;
    }

    public void setChinese(int chinese) {
        this.chinese = chinese;
    }

    public String getGrade() {
        return grade;
    }

    public void setGrade(String grade) {
        this.grade = grade;
    }
}

3、逻辑代码

package com.me.xvleihua1;

import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TabHost;
import android.widget.TextView;
import android.widget.Toast;

import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;

public class MainActivity extends AppCompatActivity {
    EditText editTextName,editTextChinese,editTextEnglish,editTextMath,editTextAge;
    TextView textViewGrade;
    Button buttonSave,buttonRead;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        editTextAge = findViewById(R.id.editTextAge);
        editTextName = findViewById(R.id.editTextName);
        editTextChinese = findViewById(R.id.editTextChinese);
        editTextEnglish = findViewById(R.id.editTextEnglish);
        editTextMath = findViewById(R.id.editTextmath);
        textViewGrade = findViewById(R.id.textViewGrade);
        buttonRead = findViewById(R.id.buttonRead);
        buttonSave = findViewById(R.id.buttonSave);
        //保存
        buttonSave.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                int math = Integer.valueOf(editTextMath.getText().toString());
                int chinese = Integer.valueOf(editTextChinese.getText().toString());
                int english = Integer.valueOf(editTextEnglish.getText().toString());
                String name = editTextName.getText().toString();
                int age = Integer.valueOf(editTextAge.getText().toString());
                Score score = new Score(math,english,chinese);
                Student student = new Student(name,age,score);
                try {
                    ObjectOutputStream objectOutputStream = new ObjectOutputStream(openFileOutput("myfile.data", MODE_PRIVATE));
                    objectOutputStream.writeObject(student);
                    objectOutputStream.flush();//清空缓存区
                    objectOutputStream.close();
                    Toast.makeText(MainActivity.this, "Data Sava!", Toast.LENGTH_SHORT).show();
                    //清空数据
                    editTextMath.getText().clear();
                    editTextChinese.getText().clear();
                    editTextEnglish.getText().clear();
                    editTextName.getText().clear();
                    editTextAge.getText().clear();
                    textViewGrade.setText("-");
                }catch (IOException e){
                    Log.e("tag","onCreate",e);
                }
            }
        });
        //读取
        buttonRead.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                try{
                    ObjectInputStream objectInputStream = new ObjectInputStream(openFileInput("myfile.data"));
                    Student student = (Student) objectInputStream.readObject();
                    editTextAge.setText(String.valueOf(student.getAge()));
                    editTextName.setText(student.getName());
                    editTextEnglish.setText(String.valueOf(student.getScore().getEnglish()));
                    editTextChinese.setText(String.valueOf(student.getScore().getChinese()));
                    editTextMath.setText(String.valueOf(student.getScore().getMath()));
                    textViewGrade.setText(student.getScore().getGrade());
                }catch (IOException e){
                    Log.e("tag","onCreate",e);
                }catch (ClassNotFoundException e){
                    Log.d("tag","onCreate",e);
                }
            }
        });

    }

}
package com.me.xvleihua1;

import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TabHost;
import android.widget.TextView;
import android.widget.Toast;

import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;

public class MainActivity extends AppCompatActivity {
EditText editTextName,editTextChinese,editTextEnglish,editTextMath,editTextAge;
TextView textViewGrade;
Button buttonSave,buttonRead;
@Override
protected void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
editTextAge = findViewById(R.id.editTextAge);
editTextName = findViewById(R.id.editTextName);
editTextChinese = findViewById(R.id.editTextChinese);
editTextEnglish = findViewById(R.id.editTextEnglish);
editTextMath = findViewById(R.id.editTextmath);
textViewGrade = findViewById(R.id.textViewGrade);
buttonRead = findViewById(R.id.buttonRead);
buttonSave = findViewById(R.id.buttonSave);
//保存
buttonSave.setOnClickListener(new View.OnClickListener() {

@Override
public void onClick(View v) {

int math = Integer.valueOf(editTextMath.getText().toString());
int chinese = Integer.valueOf(editTextChinese.getText().toString());
int english = Integer.valueOf(editTextEnglish.getText().toString());
String name = editTextName.getText().toString();
int age = Integer.valueOf(editTextAge.getText().toString());
Score score = new Score(math,english,chinese);
Student student = new Student(name,age,score);
try {
ObjectOutputStream objectOutputStream = new ObjectOutputStream(openFileOutput("myfile.data", MODE_PRIVATE));
objectOutputStream.writeObject(student);
objectOutputStream.flush();//清空缓存区
objectOutputStream.close();

Toast.makeText(MainActivity.this, "Data Sava!", Toast.LENGTH_SHORT).show();
//清空数据
editTextMath.getText().clear();

editTextChinese.getText().clear();
editTextEnglish.getText().clear();
editTextName.getText().clear();
editTextAge.getText().clear();
textViewGrade.setText("-");
}catch (IOException e){
Log.e("tag","onCreate",e);
}
}
});
//读取
buttonRead.setOnClickListener(new View.OnClickListener() {

@Override
public void onClick(View v) {

try{
ObjectInputStream objectInputStream = new ObjectInputStream(openFileInput("myfile.data"));
Student student = (Student) objectInputStream.readObject();
editTextAge.setText(String.valueOf(student.getAge()));
editTextName.setText(student.getName());
editTextEnglish.setText(String.valueOf(student.getScore().getEnglish()));
editTextChinese.setText(String.valueOf(student.getScore().getChinese()));
editTextMath.setText(String.valueOf(student.getScore().getMath()));
textViewGrade.setText(student.getScore().getGrade());
}catch (IOException e){
Log.e("tag","onCreate",e);
}catch (ClassNotFoundException e){
Log.d("tag","onCreate",e);
}
}
});

}

}

猜你喜欢

转载自www.cnblogs.com/20183544-wangzhengshuai/p/12308342.html
今日推荐