1.Serializable 介绍:
Serializable 是 Java 中的一个接口,它用于标记一个类或对象可以被序列化(即可以转换为字节流以便在网络上传输或在磁盘上持久化)。
当一个类实现 Serializable 接口时,它的对象可以被序列化,这意味着它们可以被转换为字节流,然后可以存储到文件或传输到另一个运行 Java 的系统。在需要时,这些字节流可以重新转换为对象。
要使一个类可序列化,只需添加 implements Serializable。这是一个标记接口,因此它没有方法需要实现。但是,如果一个类实现了 Serializable 接口,那么它的所有实例变量也必须是可序列化的。
在 Java 中,一些内置的类,如 String 和基本数据类型,已经实现了 Serializable 接口。你也可以让自定义的类实现这个接口,以便能够在网络上发送对象或者把对象存储到文件或数据库中。
需要注意的是,虽然 Serializable 是一个非常方便的功能,但是它并不适合所有的对象。例如,如果你的对象包含文件句柄、网络连接或者数据库连接等资源,那么这些资源在序列化过程中并不会被保存,因此当反序列化这个对象时,这些资源可能会失效。此外,如果你的对象包含循环引用,那么在序列化时可能会产生无限循环或者出现其他问题。因此,在设计对象时需要考虑到这些因素。
2.使用案例: implements Serializable
Score.java
package com.example.serializabledemo;
import java.io.Serializable;
/**
* 序列化 implements Serializable
*/
public class Score implements Serializable {
private static final long serialVersionUID = -3353717018389253119L;
private float math;
private float english;
private float chinese;
private String grade;
public Score(float math, float english, float chinese) {
this.math = math;
this.english = english;
this.chinese = chinese;
if (math >= 90 && english >= 90 && chinese >= 90) {
this.grade = "A";
} else if (math >= 80 && english >= 80 && chinese >= 80) {
this.grade = "B";
} else {
this.grade = "C";
}
}
public float getMath() {
return math;
}
public void setMath(float math) {
this.math = math;
}
public float getEnglish() {
return english;
}
public void setEnglish(float english) {
this.english = english;
}
public float getChinese() {
return chinese;
}
public void setChinese(float chinese) {
this.chinese = chinese;
}
public String getGrade() {
return grade;
}
public void setGrade(String grade) {
this.grade = grade;
}
}
Student.java
package com.example.serializabledemo;
import java.io.Serializable;
/**
* 序列化 implements Serializable
*/
public class Student implements Serializable {
private static final long serialVersionUID = 2163931301274806482L;
// 不要某个属性序列化 transient
// private transient String name;
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;
}
}
MainActivity.java
package com.example.serializabledemo;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import androidx.appcompat.app.AppCompatActivity;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
public class MainActivity extends AppCompatActivity {
private EditText etName, etAge, etMath, etChin, etEnglish;
private Button btnSave, btnLoad;
private TextView textView;
//文件名
private static final String FILE_NAME = "fileData";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
etName = findViewById(R.id.etName);
etAge = findViewById(R.id.etAge);
etChin = findViewById(R.id.etChinese);
etMath = findViewById(R.id.etMaths);
etEnglish = findViewById(R.id.etEnglish);
textView = findViewById(R.id.tvGrade);
btnSave = findViewById(R.id.btnSave);
btnLoad = findViewById(R.id.btnLoad);
//保存事件
btnSave.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
float math = Float.parseFloat(etMath.getText().toString());
float english = Float.parseFloat(etEnglish.getText().toString());
float chinese = Float.parseFloat(etChin.getText().toString());
Score score = new Score(math, english, chinese);
String name = etName.getText().toString();
int age = Integer.parseInt(etAge.getText().toString());
Student student = new Student(name, age, score);
try {
//把数据写入文件中 MODE_PRIVATE替换内容
ObjectOutputStream outputStream = new ObjectOutputStream(openFileOutput(FILE_NAME, MODE_PRIVATE));
outputStream.writeObject(student);
outputStream.flush();//刷新缓存
outputStream.close();//关闭资源
Toast.makeText(MainActivity.this, "保存文件成功!", Toast.LENGTH_SHORT).show();
//清空
etName.setText("");
etAge.setText("");
etChin.setText("");
etMath.setText("");
etEnglish.setText("");
textView.setText("");
} catch (IOException e) {
Log.e("TAG", "btnSave错误信息:", e);
}
}
});
//加载事件
btnLoad.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
//读取文件
try {
ObjectInputStream inputStream = new ObjectInputStream(openFileInput(FILE_NAME));
Student student = (Student) inputStream.readObject();
etName.setText(student.getName());
etAge.setText(String.valueOf(student.getAge()));
etChin.setText(String.valueOf(student.getScore().getChinese()));
etMath.setText(String.valueOf(student.getScore().getMath()));
etEnglish.setText(String.valueOf(student.getScore().getEnglish()));
textView.setText(student.getScore().getGrade());
inputStream.close();
} catch (IOException e) {
Toast.makeText(MainActivity.this, "文件不存在!", Toast.LENGTH_SHORT).show();
Log.e("TAG", "btnLoad错误信息:", e);
} catch (ClassNotFoundException e) {
Log.e("TAG", "btnLoad错误信息:", e);
}
}
});
}
}
布局文件 activity_main.xml
<?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">
<EditText
android:id="@+id/etName"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_marginStart="4dp"
android:ems="10"
android:hint="姓名"
android:inputType="text"
android:textSize="20sp"
app:layout_constraintBottom_toTopOf="@+id/etAge"
app:layout_constraintEnd_toStartOf="@+id/guideline4"
app:layout_constraintHorizontal_bias="0.0"
app:layout_constraintStart_toStartOf="@+id/guideline2"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.059" />
<androidx.constraintlayout.widget.Guideline
android:id="@+id/guideline2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="vertical"
app:layout_constraintGuide_percent="0.1" />
<TextView
android:id="@+id/tvGrade"
android:layout_width="0dp"
android:layout_height="77dp"
android:gravity="center"
android:hint="等级"
android:textSize="30sp"
android:textStyle="bold"
app:layout_constraintBottom_toTopOf="@+id/guideline3"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.872"
app:layout_constraintStart_toStartOf="@+id/guideline4"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.047" />
<EditText
android:id="@+id/etAge"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_marginStart="4dp"
android:ems="10"
android:hint="年龄"
android:inputType="number"
android:textSize="20sp"
app:layout_constraintBottom_toTopOf="@+id/etChinese"
app:layout_constraintEnd_toEndOf="@+id/etName"
app:layout_constraintStart_toStartOf="@+id/etName"
app:layout_constraintTop_toBottomOf="@+id/etName"
app:layout_constraintVertical_bias="0.182" />
<EditText
android:id="@+id/etMaths"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:ems="10"
android:hint="数学"
android:inputType="number"
android:textSize="20sp"
app:layout_constraintBottom_toTopOf="@+id/etEnglish"
app:layout_constraintEnd_toEndOf="@+id/etChinese"
app:layout_constraintStart_toStartOf="@+id/etChinese"
app:layout_constraintTop_toBottomOf="@+id/etChinese" />
<EditText
android:id="@+id/etChinese"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:ems="10"
android:hint="语文"
android:inputType="number"
android:textSize="20sp"
app:layout_constraintBottom_toTopOf="@+id/etMaths"
app:layout_constraintEnd_toEndOf="@+id/etAge"
app:layout_constraintStart_toStartOf="@+id/etAge"
app:layout_constraintTop_toBottomOf="@+id/etAge" />
<EditText
android:id="@+id/etEnglish"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:ems="10"
android:hint="英语"
android:inputType="number"
android:textSize="20sp"
app:layout_constraintBottom_toTopOf="@+id/guideline3"
app:layout_constraintEnd_toEndOf="@+id/etMaths"
app:layout_constraintStart_toStartOf="@+id/etMaths"
app:layout_constraintTop_toBottomOf="@+id/etMaths" />
<androidx.constraintlayout.widget.Guideline
android:id="@+id/guideline3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="horizontal"
app:layout_constraintGuide_percent="0.6" />
<Button
android:id="@+id/btnSave"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="保存"
app:layout_constraintStart_toStartOf="@+id/guideline2"
app:layout_constraintTop_toTopOf="@+id/guideline3" />
<Button
android:id="@+id/btnLoad"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="加载"
app:layout_constraintBottom_toBottomOf="@+id/btnSave"
app:layout_constraintEnd_toStartOf="@+id/guideline4"
app:layout_constraintTop_toTopOf="@+id/btnSave"
app:layout_constraintVertical_bias="0.0" />
<androidx.constraintlayout.widget.Guideline
android:id="@+id/guideline4"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="vertical"
app:layout_constraintGuide_percent="0.7" />
</androidx.constraintlayout.widget.ConstraintLayout>
生成的文件目录: