Android : 序列化 Serializable 简单应用

news2024/10/6 1:43:51

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>

生成的文件目录:

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/1306269.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

AI创新之美:AIGC探讨2024年春晚吉祥物龙辰辰的AI绘画之独特观点

&#x1f3ac; 鸽芷咕&#xff1a;个人主页 &#x1f525; 个人专栏:《粉丝福利》 《linux深造日志》 ⛺️生活的理想&#xff0c;就是为了理想的生活! 文章目录 引言一、龙辰辰事件概述二、为什么龙辰辰会被质疑AI创作&#xff1f;1.1 AI 作画的特点2.2 关于建行的合作宣传图…

命令执行RCE及其绕过详细总结(17000+字数!)

目录 操作系统连接符&#xff1a; 常见函数&#xff1a; 绕过过滤&#xff1a; 空格过滤绕过&#xff1a; 1、大括号{}&#xff1a; 2、$IFS代替空格&#xff1a; 3、重定向字符<&#xff0c;<> 4、%09绕过&#xff08;相当于Tab键&#xff09; 文件名过滤绕过…

FPGA使用乘法的方式

FPGA使用乘法的方式 方法一:直接使用乘法符“*” 源代码 module multiply(input [7:0] a,input [7:0] b,output wire [15:0] result);(*use_dsp48 = "yes"*) wire [15:0] result;assign result = a*b; endmodule仿真代码 module multiply_tb();reg [7:0] a; re…

讲座 | 颠覆传统摄像方式乃至计算机视觉的“脉冲视觉”

传统相机拍摄视频时其实是以一定帧率进行采样&#xff0c;视频其实还是一串图片的集合&#xff0c;因此低帧率时会觉得视频卡&#xff0c;拍摄高速运动物体时会有运动模糊等等问题。然而你能想象这一切都可以被“脉冲视觉”这一前沿技术改变吗&#xff1f; 今天下午听了北京大学…

Vue3-03-reactive() 响应式基本使用

reactive() 的简介 reactive() 是vue3 中进行响应式状态声明的另一种方式&#xff1b; 但是&#xff0c;它只能声明 【对象类型】的响应式变量&#xff0c;【不支持声明基本数据类型】。reactive() 与 ref() 一样&#xff0c;都是深度响应式的&#xff0c;即对象嵌套属性发生了…

C++ 教程 - 02 复合数据类型

文章目录 数组vector字符串输入输出结构体枚举指针引用综合案例 数组 相同类型的数据的集合{ }&#xff0c;通过索引访问元素&#xff1b;在内存中连续存储&#xff0c;属于顺序表&#xff1b;插入、删除时间复杂度 O ( n ) O(n) O(n)&#xff0c;访问复杂度 O ( 1 ) O(1) O(1…

python:五种算法(SSA、WOA、GWO、PSO、GA)求解23个测试函数(python代码)

一、五种算法简介 1、麻雀搜索算法SSA 2、鲸鱼优化算法WOA 3、灰狼优化算法GWO 4、粒子群优化算法PSO 5、遗传算法GA 二、5种算法求解23个函数 &#xff08;1&#xff09;23个函数简介 参考文献&#xff1a; [1] Yao X, Liu Y, Lin G M. Evolutionary programming made…

机器学习-KL散度的直观理解+代码

KL散度 直观理解&#xff1a;KL散度是一种衡量两个分布之间匹配程度的方法。通常在概率和统计中&#xff0c;我们会用更简单的近似分布来代替观察到的数据或复杂的分布&#xff0c;KL散度帮我们衡量在选择近似值时损失了多少信息。 在信息论或概率论中&#xff0c;KL散度&#…

鸿蒙(HarmonyOS)应用开发——简易版轮播图

简述 轮播图在应用中&#xff0c;已经很常见的展现方式。像uniapp、iview&#xff0c;viewUI等前端组件框架&#xff0c;都提供了轮播图组件。那么在harmonyOS中&#xff0c;如果要实现轮播&#xff0c;我们是使用swiper 组件 swiper组件 swiper 组件是一种容器组件。它提供…

汽车销售技巧培训应该学习哪些内容

汽车销售技巧培训应该学习哪些内容 随着汽车市场的竞争日益激烈&#xff0c;汽车销售技巧培训对于提高销售人员的销售能力和服务水平至关重要。本文将介绍汽车销售技巧培训应该学习哪些内容&#xff0c;并结合案例进行分析。 一、产品知识 作为销售人员&#xff0c;了解所销售…

汽车IVI中控开发入门及进阶(十一):ALSA音频

前言 汽车中控也被称为车机、车载多媒体、车载娱乐等,其中音频视频是非常重要的部分,音频比如播放各种格式的音乐文件、播放蓝牙接口的音乐、播放U盘或TF卡中的音频文件,如果有视频文件也可以放出音频,看起来很简单,在windows下音乐播放器很多,直接打开文件就能播放各…

python冒泡排序

冒泡排序思想 大家可以把我们所有的需要排列的数字想象成一个水中的气泡&#xff0c;大的数字想象成大气泡&#xff0c;小的数字想象成小气泡。 其实冒泡排序就是比较相邻的两个数字的大小&#xff0c;然后大的数字排在小的数字的后面&#xff0c;我们依次比较&#xff0c;第一…

2. 如何通过公网IP端口映射访问到设备的vmware虚拟机的ubuntu服务器

文章目录 1. 主机设备是Windows 11系统2. 安装vmware虚拟机3. 创建ubuntu虚拟机&#xff08;据说CentOS 7 明年就不维护了&#xff0c;就不用这个版本的linux了&#xff09;4. 安装nginx服务:默认端口805. 安装ssh服务:默认端口226. 设置主机 -> ubuntu的端口映射7. 设置路由…

ARM开发基础知识

1、ARM寄存器 概念&#xff1a;寄存器是处理器内部的存储器&#xff0c;没有地址 作用&#xff1a;一般用于暂时存储参与运算的数据和运算结果 分类&#xff1a;通用寄存器、专用寄存器、状态寄存器 注意&#xff1a;有标签&#xff08;带三角光标&#xff09;的是独有的寄存器…

【Jeecg Boot 3 - 第二天】1.2、jar 包和 lib 依赖分离,部署包缩小100倍

一、场景 二、思路 三、实战 ▶ 2.1、项目 jar 包解压获取 lib config Stage 1&#xff1a;正常打包获取 jeecg-system-start-3.6.0.jar Stage 2&#xff1a;解压 获取如下文件 Stage 3&#xff1a;获取 lib config ▶ 2.2、获取简化版项目jar包 Stage 1&#xff1…

在 Debian 12 上安装 Docker

解如何在 Debian 12 上正确安装 Docker。还要学习在没有 sudo 的情况下运行 Docker&#xff0c;并在不需要时将其删除。 想在 Debian 12 上使用 Docker&#xff1f;让我来帮助你。 Docker 可以从 Debian 存储库安装。您所要做的就是运行此命令&#xff1a; sudo apt install…

Elasticsearch:使用 Elasticsearch 向量搜索及 RAG 来实现 Chatbot

Elasticsearch 的向量搜索为我们的语义搜索提供了可能。而在人工智能的动态格局中&#xff0c;检索增强生成&#xff08;Retrieval Augmented Generation - RAG&#xff09;已经成为游戏规则的改变者&#xff0c;彻底改变了我们生成文本和与文本交互的方式。 RAG 使用大型语言模…

十三、YARN资源分配调用

1、为什么要先学习YARN组件&#xff1f; 在Hadoop文件系统中&#xff0c;YARN作为Hadoop系统的第三大组件&#xff0c;其中&#xff0c;第二大组件MapReduce组件是基于YARN运行的&#xff0c;即没有YARN无法运行MapReduce程序&#xff0c;所以需要同时学习YARN。 2、YARN &…

机器人纯阻抗控制接触刚性环境(阻尼影响因素)

问题描述 在机器人学中&#xff0c;阻抗控制是一种常用的控制策略&#xff0c;用于管理机器人在与环境交互时的运动和力。阻抗控制背后的关键概念是将环境视为导纳&#xff0c;而将机器人视为阻抗。 纯阻抗控制接触刚性环境时&#xff0c;机器人的行为方式主要受其阻抗参数的…

Python 自动化之批量处理文件(一)

批量新建目录、文档Pro版本 文章目录 批量新建目录、文档Pro版本前言一、做成什么样子二、基本思路1.引入库2.基本架构 三、用户输入模块四、数据处理模块1.excel表格数据获取2.批量数据的生成 总结 前言 我来写一个不一样的批量新建吧。在工作中&#xff0c;有些同学应该会遇…