Android--序列化/数据存入、读出SD卡

本文介绍了序列化的概念及其在Android中的应用,包括如何使用serializable和Parcelable进行对象序列化,并提供了具体的代码实例,展示了如何将对象写入SD卡以及从SD卡读取。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

序列化
内外存储写对象,需要写对象,在内存中传递对象,A activity 传入b activity中需要序列化。
序列化两种:serializable、Parcelable
支持可序列化:
对象读写文件推荐使用:serializable
在JAVA中建议使用Parcelable

例题:将数据传入SD卡中,启动就会读取
这里写图片描述
本题有两种方法:1.传入字符串:读取时根据分割字符读取
2.传入一个实体类
本题中使用第一种,在此给出第二种的方法

//传进去一个Object类
       ok.setOnClickListener(new View.OnClickListener() {
           @Override
          public void onClick(View v) {
              Message message=new Message();
              message.setTitle(c1.isChecked());
            message.setChajian(c3.isChecked());
               message.setInformation(c2.isChecked());
              message.setRead(c4.isChecked());
               message.setCollection(c5.isChecked());
               message.setCollection(c6.isChecked());
                message.setSize(tv3.getText().toString());
String statu=Environment.getExternalStorageState();
   if (!statu.equals(Environment.MEDIA_MOUNTED)){
      Toast.makeText(SettingSDActivity.this,"SD卡未就绪",Toast.LENGTH_SHORT).show();
               return ;
            }

 File root=Environment.getExternalStorageDirectory();
               FileOutputStream fos=null;
              ObjectOutputStream oos=null;
               try {
                  fos=new FileOutputStream(root+"/settings.txt");
                   try {
                     oos=new ObjectOutputStream(fos);
                      oos.writeObject(message);
                  } catch (IOException e) {
                      e.printStackTrace();
                   }
               } catch (FileNotFoundException e) {
                   e.printStackTrace();
             }finally {
                  if (fos != null) {
                      try {
                          fos.close();
                      fos.flush();
                     } catch (IOException e) {
                           e.printStackTrace();
                      }
                    }
                }
           }
      });
     }

下面是实体对象的class文件
此处继承了Serializable 接口,实现序列化

public class Message implements Serializable {
    private Boolean title;
    private String size;
    private Boolean information;
    private Boolean chajian;
    private Boolean read;
    private Boolean collection;
    private Boolean top;

    public Message(Boolean title, String size, Boolean information, Boolean chajian, Boolean read, Boolean collection, Boolean top) {
        this.title = title;
        this.size = size;
        this.information = information;
        this.chajian = chajian;
        this.read = read;
        this.collection = collection;
        this.top = top;
    }

    public Boolean getTitle() {
        return title;
    }

    public void setTitle(Boolean title) {
        this.title = title;
    }

    public String getSize() {
        return size;
    }

    public void setSize(String size) {
        this.size = size;
    }

    public Boolean getInformation() {
        return information;
    }

    public void setInformation(Boolean information) {
        this.information = information;
    }

    public Boolean getChajian() {
        return chajian;
    }

    public void setChajian(Boolean chajian) {
        this.chajian = chajian;
    }

    public Boolean getRead() {
        return read;
    }

    public void setRead(Boolean read) {
        this.read = read;
    }

    public Boolean getCollection() {
        return collection;
    }

    public void setCollection(Boolean collection) {
        this.collection = collection;
    }

    public Boolean getTop() {
        return top;
    }

    public void setTop(Boolean top) {
        this.top = top;
    }

    public Message() {

    }

}

下面为第一种方法代码:需要注意的是开始没有文件,会报错,需要加如判断。

public class SettingSDActivity extends AppCompatActivity {
    private CheckBox c1,c2,c3,c4,c5,c6;
    private TextView tv3,ok;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_setting_sd);
        c1=(CheckBox)findViewById(R.id.c1);
        c2=(CheckBox)findViewById(R.id.c2);
        c3=(CheckBox)findViewById(R.id.c3);
        c4=(CheckBox)findViewById(R.id.c4);
        c5=(CheckBox)findViewById(R.id.c5);
        c6=(CheckBox)findViewById(R.id.c6);
        tv3=(TextView)findViewById(R.id.tv3);
        ok=(TextView)findViewById(R.id.ok);
        tv3.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                AlertDialog.Builder builder=new AlertDialog.Builder(SettingSDActivity.this);
                builder.setTitle("字体大小请选择");
                builder.setIcon(R.mipmap.ic_launcher);
                final String[] items={"大","中","小"};
                // builder.setMultiChoiceItems()多选
                builder.setSingleChoiceItems(items, 1, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int i) {
                        Toast.makeText(getBaseContext(), items[i].toString(), Toast.LENGTH_SHORT).show();
                        tv3.setText(items[i].toString());
                        dialog.dismiss();
                    }
                });
                builder.setCancelable(false);
                AlertDialog alertDialog=builder.create();
                alertDialog.show();
            }
        });

        ok.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                saveFile();
            }
        });

//保存到SD卡上,
    public  void saveFile(){
        FileOutputStream fos=null;
        //获取SD卡状态
        String state= Environment.getExternalStorageState();
        //判断SD卡是否就绪
        if(!state.equals(Environment.MEDIA_MOUNTED)){
            Toast.makeText(this, "请检查SD卡", Toast.LENGTH_SHORT).show();
            return;
        }
        //取得SD卡根目录
        File file= Environment.getExternalStorageDirectory();
        try {
            Log.d("=====SD卡根目录:", file.getCanonicalPath().toString());
            //输出流的构造参数1:可以是File对象,也可以是文件路径
            //输出流的构造参数2:默认为fasle=>覆盖内容:true=>追加内容
//            File myFile=new File(file.getCanonicalPath()+"/sd.txt");
//            fos=new FileOutputStream(myFile);
            //加true追加模式
            //文件位置
            fos=new FileOutputStream(file.getCanonicalPath()+"/sd.txt");
            String  str=content();
            fos.write(str.getBytes());
            Toast.makeText(this,"保存成功",Toast.LENGTH_SHORT).show();
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            if (fos!=null){
                try {
                    fos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
    public String content(){
        String a,b,c,d,e,f,g,h;
        if(c1.isChecked()){
            a="check";
        }else{
            a="uncheck";
        }
        if(c2.isChecked()){
            b="check";
        }else{
            b="uncheck";
        }
        if(c3.isChecked()){
            c="check";
        }else{
            c="uncheck";
        }
        if(c4.isChecked()){
            d="check";
        }else{
            d="uncheck";
        }
        if(c5.isChecked()){
            e="check";
        }else{
            e="uncheck";
        }
        if(c6.isChecked()){
           f="check";
        }else{
            f="uncheck";
        }
        g=tv3.getText().toString();
        h=a+"#"+g+"#"+b+"#"+c+"#"+d+"#"+e+"#"+f;
        return h;
    }

//读取文件
    public String  readFile(){
        BufferedReader reader=null;
        FileInputStream fis=null;
        StringBuilder sbd=new StringBuilder();
        String statu=Environment.getExternalStorageState();
        if (!statu.equals(Environment.MEDIA_MOUNTED)){

            Toast.makeText(this,"SD卡未就绪",Toast.LENGTH_SHORT).show();
            return  "";
        }
        //拿到SD卡根目录
        File root=Environment.getExternalStorageDirectory();
        try {
            fis=new FileInputStream(root+"/sd.txt");
            reader= new BufferedReader(new InputStreamReader(fis));
            String row="";
            try {
                while ((row=reader.readLine())!=null){

                    sbd.append(row);
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        } catch (FileNotFoundException e) {
            Toast.makeText(this,"文件不存在",Toast.LENGTH_SHORT).show();
            e.printStackTrace();
        }finally {
            if (reader!=null){
                try {
                    reader.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return  sbd.toString();
    }


//一开始就读取
    @Override
    protected void onStart() {
        super.onStart();
        String my = readFile();
        if(my != ""){
            String k[] = my.split("#");
            if (k[0].equals("check")) {
                c1.setChecked(true);
            } else {
                c1.setChecked(false);
            }
            tv3.setText(k[1]);
            if (k[2].equals("check")) {
                c2.setChecked(true);
            } else {
                c2.setChecked(false);
            }
            if (k[3].equals("check")) {
                c3.setChecked(true);
            } else {
                c3.setChecked(false);
            }
            if (k[4].equals("check")) {
                c4.setChecked(true);
            } else {
                c4.setChecked(false);
            }
            if (k[5].equals("check")) {
                c5.setChecked(true);
            } else {
                c5.setChecked(false);
            }
            if (k[6].equals("check")) {
                c6.setChecked(true);
            } else {
                c6.setChecked(false);
            }
        }
       }
}

接下来是布局文件

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <LinearLayout
        android:orientation="vertical"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_gravity="center_horizontal">

    </LinearLayout>

    <ScrollView
        android:layout_width="match_parent"
        android:layout_height="match_parent">
        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:orientation="vertical"
            >
            <LinearLayout
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:orientation="horizontal"
                android:layout_marginTop="10dp"
                android:layout_marginBottom="10dp"
                >
                <TextView
                    android:layout_width="280dp"
                    android:layout_height="wrap_content"
                    android:text="设置"
                    android:textSize="25sp"
                    android:gravity="center"
                    />
                <TextView
                    android:id="@+id/ok"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:text="提交"
                    android:textSize="25sp"
                    />

            </LinearLayout>
            <LinearLayout
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:orientation="horizontal"
                android:layout_marginTop="10dp"
                android:layout_marginBottom="10dp"
                >
                <TextView
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:text="列表显示摘要"
                    android:textSize="25sp"

                    />
                <CheckBox
                    android:id="@+id/c1"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:textSize="25sp"
                    android:layout_marginLeft="150dp"
                    />
            </LinearLayout>
            <View
                android:layout_width="match_parent"
                android:layout_height="1dp"
                android:background="#a9a8a8"
                ></View>
            <LinearLayout
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:orientation="horizontal"
                android:layout_marginTop="10dp"
                android:layout_marginBottom="10dp"
                android:id="@+id/LL1"
                >
                <TextView
                    android:id="@+id/tv2"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:text="字体大小"
                    android:textSize="25sp"
                    />
                <TextView
                    android:id="@+id/tv3"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:text="中 >"
                    android:textSize="25sp"
                    android:layout_marginLeft="205dp"
                    />
            </LinearLayout>
            <View
                android:layout_width="match_parent"
                android:layout_height="1dp"
                android:background="#a9a8a8"
                ></View>
            <LinearLayout
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:orientation="horizontal"
                android:layout_marginTop="10dp"
                android:layout_marginBottom="10dp"
                >
                <TextView
                    android:id="@+id/tv4"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:text="列表页评论"
                    android:textSize="25sp"
                    />
                <TextView
                    android:id="@+id/tv5"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:text="不限 >"
                    android:textSize="25sp"
                    android:layout_marginLeft="153dp"
                    />
            </LinearLayout>
            <View
                android:layout_width="match_parent"
                android:layout_height="1dp"
                android:background="#a9a8a8"
                ></View>
            <LinearLayout
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:orientation="horizontal"
                android:layout_marginTop="10dp"
                android:layout_marginBottom="10dp"
                >
                <TextView
                    android:id="@+id/tv6"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:text="2G/3G网络流量"
                    android:textSize="25sp"
                    />
                <TextView
                    android:id="@+id/tv7"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:text="较省流量(普通下载)>"
                    android:textSize="15sp"
                    android:layout_marginLeft="15dp"
                    />
            </LinearLayout>
            <View
                android:layout_width="match_parent"
                android:layout_height="1dp"
                android:background="#a9a8a8"
                ></View>
            <LinearLayout
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:orientation="horizontal"
                android:layout_marginTop="10dp"
                android:layout_marginBottom="10dp"
                >
                <TextView
                    android:id="@+id/tv8"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:text="清理缓存"
                    android:textSize="25sp"
                    />
                <TextView
                    android:id="@+id/tv9"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:text="当前缓存:2.48MB>"
                    android:textSize="20sp"
                    android:layout_marginLeft="70dp"
                    />
            </LinearLayout>
            <View
                android:layout_width="match_parent"
                android:layout_height="1dp"
                android:background="#a9a8a8"
                ></View>
            <LinearLayout
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:orientation="horizontal"
                android:layout_marginTop="10dp"
                android:layout_marginBottom="10dp"
                >
                <TextView
                    android:id="@+id/tv10"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:text="推送通知"
                    android:textSize="25sp"
                    />
                <CheckBox
                    android:id="@+id/c2"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_marginLeft="200dp"
                    />
            </LinearLayout>
            <View
                android:layout_width="match_parent"
                android:layout_height="1dp"
                android:background="#a9a8a8"
                ></View>
            <LinearLayout
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:orientation="horizontal"
                android:layout_marginTop="10dp"
                android:layout_marginBottom="10dp"
                >
                <TextView
                    android:id="@+id/tv11"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:text="互动插件"
                    android:textSize="25sp"
                    />
                <CheckBox
                    android:id="@+id/c3"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_marginLeft="200dp"
                    />
            </LinearLayout>
            <View
                android:layout_width="match_parent"
                android:layout_height="1dp"
                android:background="#a9a8a8"
                ></View>
            <LinearLayout
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:orientation="horizontal"
                android:layout_marginTop="10dp"
                android:layout_marginBottom="10dp"
                >
                <TextView
                    android:id="@+id/tv12"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:text="自动优化阅读"
                    android:textSize="25sp"
                    />

                <CheckBox
                    android:id="@+id/c4"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_marginLeft="152dp"
                    />
            </LinearLayout>
            <View
                android:layout_width="match_parent"
                android:layout_height="1dp"
                android:background="#a9a8a8"
                ></View>
            <LinearLayout
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:orientation="horizontal"
                android:layout_marginTop="10dp"
                android:layout_marginBottom="10dp"
                >
                <TextView
                    android:id="@+id/tv13"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:text="收藏时转发"
                    android:textSize="25sp"
                    />
                <CheckBox
                    android:id="@+id/c5"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"

                    android:layout_marginLeft="175dp"
                    />
            </LinearLayout>
            <View
                android:layout_width="match_parent"
                android:layout_height="1dp"
                android:background="#a9a8a8"
                ></View>
            <LinearLayout
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:orientation="horizontal"
                android:layout_marginTop="10dp"
                android:layout_marginBottom="10dp"
                >
                <TextView
                    android:id="@+id/tv14"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:text="顶踩时转发"
                    android:textSize="25sp"
                    />
                <CheckBox
                    android:id="@+id/c6"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_marginLeft="175dp"
                    />
            </LinearLayout>
            <View
                android:layout_width="match_parent"
                android:layout_height="1dp"
                android:background="#a9a8a8"
                ></View>

        </LinearLayout>

    </ScrollView>
</LinearLayout>

实现效果如下:
这里写图片描述

这里写图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值