序列化存儲(chǔ)磁盤
package com.example.myapplication;
import android.os.Bundle;
import android.util.Log;
import androidx.appcompat.app.AppCompatActivity;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.util.ArrayList;
public class MainActivity extends AppCompatActivity {
private String TAG = "MainActivity";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ArrayList<String> strings = new ArrayList<>();
strings.add("a");
strings.add("b");
strings.add("c");
//存儲(chǔ)數(shù)據(jù)集合,也可以是實(shí)體類
init(strings);
}
private void init(Serializable serializable) {
try {
Log.i(TAG, "init: " + serializable);
String serialize = serialize(serializable); //序列化
Log.i(TAG, "序列化: " + serializable);
ArrayList<String> serializable1 = (ArrayList<String>) deSerialization(serialize); //用序列化返回的信息取反序列化
Log.i(TAG, "反序列化: " + serializable1);
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
//序列化 存儲(chǔ)在磁盤
private static String serialize(Serializable serializable) throws IOException {
long startTime = System.currentTimeMillis();
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
ObjectOutputStream objectOutputStream = new ObjectOutputStream(byteArrayOutputStream);
objectOutputStream.writeObject(serializable);
String serStr = byteArrayOutputStream.toString("ISO-8859-1");
serStr = URLEncoder.encode(serStr, "UTF-8");
objectOutputStream.close();
byteArrayOutputStream.close();
Log.d("MainActivity", "serialize str =" + serStr);
long endTime = System.currentTimeMillis();
Log.d("MainActivity", "序列化耗時(shí)為:" + (endTime - startTime));
return serStr;
}
/**
* 反序列化對(duì)象
*
* @param str
* @return
* @throws IOException
* @throws ClassNotFoundException
*/
private static Serializable deSerialization(String str) throws IOException, ClassNotFoundException {
long startTime = System.currentTimeMillis();
String redStr = URLDecoder.decode(str, "UTF-8");
ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(redStr.getBytes("ISO-8859-1"));
ObjectInputStream objectInputStream = new ObjectInputStream(byteArrayInputStream);
Serializable serializable = (Serializable) objectInputStream.readObject();
objectInputStream.close();
byteArrayInputStream.close();
long endTime = System.currentTimeMillis();
Log.d("MainActivity", "反序列化耗時(shí)為:" + (endTime - startTime));
return serializable;
}
}
日志如下